I’ve scoured the Codex, failed to get get_page_by_title() to work and am quite surprised that there doesn’t seem to be a standard WP function for this task.
I need to get the ID of any given post/ cpt or page using either the slug of the post/ page title. Ideally I’m looking for the following:
get_post_ID_by_title('My post title', 'customposttype');
What should I be doing?
Update: As of WordPress 3.0 you can use the built-in function
get_page_by_title
with the third parameter$post_type
:Original Answer
you can use this function that jumps by google “get post by title”
You are missing a function parameter. Throw a null in for the second optional paramter $output and this function should work for you.
I just ran into the same issue and adding the null fixed it for me.
I tend to shy away from direct DB queries. Instead, I use the
WP_Query
object to parse things for me.This is, basically, a function I use in one of my themes to get a post based on a given slug:
This will create a query using the WP API to fetch a post of a specific type with a given slug, will run the regular loop functions on the result, and return the ID of the post. You could also use it to return the entire post by modifying the function a bit, but that’s up to you.
This is a few years old now, but it still pops up when searching for this on Google. So, here’s a simple way to do it:
or
Then just use the $page object to grab the ID:
Currently (WP >4.9.2) you’ll find your “any” given post/page etc. by title/slug this way: