Get Post ID from Post Title in WordPress

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

Add this in child theme‘s functions.php or a code snippets plugin:

// Function to get post ID given the post title
function bl_get_post_id_by_title( $title = '' ) {
	// if $title is not provided, return current post ID
	if ( $title === '' ) {
		return get_the_ID();
	}

	// get post object from the post title
	$post_object = get_page_by_title( $title, OBJECT, 'post' );

	// return the post ID
	return $post_object->ID;
}

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://developer.wordpress.org/reference/functions/get_page_by_title/

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

  • 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