Update: The get_page_by_title() function now includes a third parameter that allows you to specify the post_type. You can use this parameter to get pages, posts or custom taxonomies. The below function is no longer needed.
Recently, I needed to retrieve posts and pages in WordPress based on their title. I digged into WordPress code to find out the function that can do it, but to my surprise, I found out that there isn’t a function that could work both for pages and posts.
Some people might argue that the easy way is to query the database directly, but I generally try to use a build-in function if available rather than querying the database directly.
After some poking around in the wp-hackers maling list and #wordpress irc channel, I used the following code in my Plugin. I thought of sharing this here, so that it could be helpful to others.
Retrieving pages based on title
For pages, there is a built-in function get_page_by_title() which we can use. The code would be
Retrieving posts based on title
For posts, we don’t have a built-in function. We have to manually query the database. I have written a function which can do this.
Retrieving multiple posts based on title
If you have more than one post with the same title, then the above function will return only the first post. If you want to retrieve all the posts which have the title, then you can use the below function. Thanks Jerry.
Including this as part of the core
As I said before, I always prefer to use a built-in function rather than querying the database directly. I am planning to add a new ticket to WordPress trac to add this function to the core. Will keep you all updated about the ticket status.
Update: I have created a ticket in WordPress trac, to add this function to the core. Let’s hope it gets to the core.
- WordPress Developer tools to increase productivity in WordCamp Mumbai
- Email Log WordPress plugin v1.9.1 released
- Email Log WordPress plugin v1.9 released
- How to find if you are on the last page of a multi-page post in WordPress
- Easy Retweet WordPress plugin v3.1 Released
- Creating custom tables with correct Character Set and Collation in WordPress