20th Jan '23
/
6 comments

Get Post ID from Post Title in WordPress

Updated on 18 May 2023

Looking for a way to get a Post ID given its title on single posts in WordPress?

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

// Function to get WordPress post ID given the post title
function bl_get_post_id_by_title( string $title = '' ): int {
    $posts = get_posts(
        array(
            'post_type'              => 'post',
            'title'                  => $title,
            'numberposts'            => 1,
            'update_post_term_cache' => false,
            'update_post_meta_cache' => false,
            'orderby'                => 'post_date ID',
            'order'                  => 'ASC',
            'fields'                 => 'ids'
        )
    );

    return empty( $posts ) ? get_the_ID() : $posts[0];
}

The function is set to return the current post ID if there is no matching post having the supplied title text.

With our custom function in place here’s a sample usage:

<?php

echo bl_get_post_id_by_title( 'Digitized motivating structure' );

where “Digitized motivating structure” is the title of the Post. It is not case-sensitive.

Sample output:

2165

To use this in Bricks’ dynamic data:

{echo:bl_get_post_id_by_title(Digitized motivating structure)}

References

https://make.wordpress.org/core/2023/03/06/get_page_by_title-deprecated/

https://academy.bricksbuilder.io/article/dynamic-data/#:~:text=Bricks%201.4%20introduces,support%20double%20quotes

Get access to all 610 Bricks code tutorials with BricksLabs Pro

6 comments

  • I was just wondering if you could clarify the benefit of including string and int, it's not required for the function to work so is it performance? Personal preference? Other?

    • A

      The argument type declaration (string in this case) ensures that the function only takes in a string.

      The return type declaration (int in this case) makes it clear to 'client code' (code that uses the function) that the function will return an integer.

      These are considered good practices and a better option compared to adding comments to the function definitions about what the parameter types and return type should be.

      If you want to learn more, I recommend reading this book: PHP 8 Objects, Patterns, and Practice by Matt Zandstra.

  • get_page_by_title is deprecated

  • Eric Embacher

    Rather than specifying the title like "Digitized motivating structure" the title is the title of the post specified by the relationship field. In other words, I am executing this on a "hotel" post. Each hotel is associated with a "Region" post. I need to output the ID of the Region associated with the current post.

Leave your comment