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 526 Bricks code tutorials with BricksLabs Pro

4 comments

  • 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