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/
6 comments
Matt
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?
Sridhar Katakam
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.
Jimbo
get_page_by_title is deprecated
Sridhar Katakam
Updated.
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.
Sridhar Katakam
What is the Return Format of your Relationship of field? Post Object or Post ID?