Retrieving posts and pages based on title in WordPress

Retrieving posts and pages based on title in WordPress

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

$page = get_page_by_title(‘post title that we are searching’);
// $page is the post array. To just retrieve the id
$id = $page->ID;

Retrieving pages 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.

/**
* Retrieve a post given its title.
*
* @uses $wpdb
*
* @param string $post_title Page title
* @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
* @return mixed
*/
function get_post_by_title($page_title, $output = OBJECT) {
    global $wpdb;
        $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='post'", $page_title ));
        if ( $post )
            return get_post($post, $output);
 
    return null;
}

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 get’s to the core.

Possibly Related posts

Tags:

Share thy love

11 Comments so far

Trackback URI | 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
    ?>

    • Sudar says:

      Use this code to get the post title based on id

      $my_id = 7;
      $post_id_7 = get_post($my_id);
      $title = $post_id_7->post_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.

1 Tweetbacks so far

Leave a Comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">