Retrieving posts and pages based on title in WordPress

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.

Related posts

Tags:

28 Comments so far

Follow up comments through RSS Feed | Post a comment

  • Ozh says:

    One little thing: your code snippets have html entities, this might confuse someone who won’t pay enough attention before cut’n pasting your code 🙂

    How does the function perform if you enter a slightly wrong page title? (eg “my new plugin rocks” instead of “my new plugin rocks hard”)

    • Sudar says:

      @Ozh,

      The function get_page_by_title() (wp_includes/post.php) matches only exact strings, so slightly wrong title will not work. The following is the query used by the function.

      $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='page'", $page_title )

      Thanks for pointing out about the issue with html encoding. Fixed it now 🙂

  • Christian says:

    Yeah, it’s stupid that this isn’t part of core: get_page_by_title() has been there since 2.1 and all it would require is an extra param to switch between post title requests and page title requests. I guess the reason is that this is of limited use, in that many posts/pages can have the same name, yet this function only returns the first it comes across. Good luck getting this into core…

  • Aaron says:

    Thank you for sharing this!!!!

  • Daniel says:

    Hello ,
    Can anyone tell me How can I display(retrieve) the page title if I know the page ID ? :
    I get this code from WordPress codex and instead of ID 123 I need to put custom field . But it doesn’t work-:(

    post_title; // Get title
    ?>

    …..and This is the probably bad code I created :

    <?php
    $page_id = post->ID;
    echo get_post_meta($postid, ‘customField’, true);
    ?>;
    $page_data = get_page( $page_id );
    $title = $page_data->post_title; // Get title
    ?>

    Any help will be appreciated.

  • Daniel says:

    Sorry i didn’t mention that here is the code tag

    WordPress Codex:

    post_title; // Get title
    ?>

    my bad code :

    <?php
    $page_id = post->ID;
    echo get_post_meta($postid, 'customField', true);
    ?>;
    $page_data = get_page( $page_id );
    $title = $page_data->post_title; // Get title
    ?>

  • Daniel says:

    Thanks for your respond
    But the link is this article , i have read it before , but i need to do it on contrary , i know the ID and i need to display page title with a little help of custom field,
    for example:
    I need the people to find the name of the page by ID number (it is easier to remember ID than title – title name you can be mistaken ) so I would like to put the ID nr. into custom field input in the form , like this i will get the ID like a custom field , which will create link to that page link and next to it I want to automaticly display the correct title of that page (I have changed WP pages into Girls Portfolios so every girl has her own ID )I only want the people can find them by ID

    the code maybe should be like this:

    <?php
    $page = get_page_by_id(‘post->ID;
    echo get_post_meta($postid, 'friend1', true);
    ?>’);
    $id = $page->title;
    ?>

  • Daniel says:

    thanks again – but in your code i need 3times repeat the ID number(7) , in this case i need 3 times put custom field codeto display number 7 to finally get the page title , is there something more simple where i can put : get_meta_custom field instead the ID number (7)?
    In my case the people has to submit the number in form , after this number will change into custom field .
    in Other words i dont know how to implement custom field code(ID number) into (ID to TITLE code)

  • John says:

    They have stated in the trac that they have added the parameter for posts in the get_page_by_title function for posts and post types, but I don’t know exactly how to form the code.

    Going to use yours until there is some documentation.

  • I don’t know if you can help me … but I want to show related post based on one part of the title … I have thousand galleries … and I would like to put related galleries based on name before a @

    example :

    http://www.le-hiboo.com/27104-izia-olympia-paris-14-11-2010

    I would like to put after this gallery all galleries (same category, so) of Izia

    All my galleries are built as name of the artist @ name of the venue, name of the town | JJ.MM.YYYY

    I don’t know if it’s possible, but it seems your article is going on this way …

    thank you !

    • Sudar says:

      It is possible, but I guess it could be slightly complicated. You might have to change the queries a bit. I guess it would be better if you hire a freelancer to do it.

  • hassan says:

    thanks man its work fine for my website
    but sorry i want url from post title so i modify you code like this

    function get_post_url_by_title($post_title, $output = OBJECT) {
    global $wpdb;
    $sqlquery=”SELECT ID FROM $wpdb->posts WHERE post_title like ‘%$post_title%’ AND post_type=’post’ AND `post_status`=’publish'”;
    $pageposts = $wpdb->get_results($sqlquery, OBJECT);
    //var_dump($pageposts); //object
    $url=$pageposts[0]->ID;
    if(empty($url))
    {
    return “coming-soon”;
    }

    else
    {
    return get_permalink($pageposts[0]->ID);
    }
    }

  • chaos1 says:

    How would I get the ID based on title? My head is going to freak out I’m so puzzled.

    What I want to happen outside the loop:

    $page = get_page_by_title( ‘My Page’);
    echo $page->ID; // or echo $page[‘ID’]

    in browser:

    45

    Why am I not able to do this? what do I need to do? My head hurts.

  • chaos1 says:

    I answered my own frustration. Here is my first addition to the Codex ID) )
    $content = “Hello World!”;
    return $content;
    }

    add_filter(‘the_content’, ‘my_content’);

  • Leo Plaw says:

    Thanks for this simple routine. 8)
    I agree, it should be in the core. I disagree with Christian that it would be of limited use. Google for “wordpress get post page by tite” and you will see the demand for this.

  • Hey guys, if you look properly at get_page_by_title function, you’ll find out that it has 3 parameters: get_page_by_title($page_title, $output = OBJECT, $post_type = ‘page’ ) – so just set the $post_type to whatever you want (‘post’ or your custom post type) and that’s it! it’s very confusing, I know, but nothing stops you from writing your own function:

    get_post_by_title($title, $post_type = ‘post’) {
    return get_page_by_title($title, OBJECT, $post_type);
    }

  • MR. D says:

    I spend masive time on it, and the answer is very simple:
    get_page_by_title(‘your post name’,object,’post’)

    that’s it

    • Sudar says:

      The get_page_by_title() function was not accepting the $post_type when I wrote this post. Now it seems to accept the new parameter.

      I have updated the post with this information.

  • jerry says:

    Hi Sudar,
    get_page_by_title() function only shows the post with the smallest ID If more than one post uses the same title, I am seeking the solution to return all IDs with same title, could you please help? Thank you.

    Jerry

1 Tweetbacks so far

2 Trackbacks/Pingbacks so far

Leave a Reply

Your email address will not be published. Required fields are marked *