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/