2

In my plugin, I need to find any posts of a custom post type that have a certain title. I was using this:

$my_post = get_page_by_title( $title, OBJECT, 'my_custom_post_type' );

This works great, but if there is more than one post with the same title, get_page_by_title will only return one result. According to the Codex article on get_page_by_title, this is the correct behavior for the function.

How do I retrieve all the posts with a given title, rather than just one?

5

You will need to create a new function. My example is a fork of the core function. The following will allow you to create a query across all published posts regardless of post_type, unless you desire that specific set.

function get_posts_by_title($page_title, $post_type = false, $output = OBJECT ) {
    global $wpdb;

    //Handle specific post type?
    $post_type_where = $post_type ? 'AND post_type = %s' : '';

    //Query all columns so as not to use get_post()
    $results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_title = %s $post_type_where AND post_status = 'publish'", $page_title, $post_type ? $post_type : '' ) );

    if ( $results ){
        $output = array();
        foreach ( $results as $post ){
            $output[] = $post;
        }
        return $output;
    }
    return null;
}

//This should get you an array of all posts with 'Foo Bar' as the title
get_posts_by_title('Foo Bar');
2
  • Thanks. It works well except that the 'AND' in the query string before $post_type_where needs to be removed. Jul 25 '13 at 20:22
  • Good catch! I updated my code. Jul 25 '13 at 21:32
1

I searched around the internet too for this and couldn't find anything, so to me, the most valuable part of this question is verifying that nothing better is built into Wordpress. The following is the best way I know.

The main difference between this and the marked answer is that it returns real WP_Post objects, and doesn't ignore the $output parameter.

function get_pages_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) {
    global $wpdb;

    $prepared = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = %s AND post_status = 'publish' ORDER BY ID", $page_title, $post_type );
    $results = $wpdb->get_results( $prepared );
    $post_ids = array_map( function($x) { return intval($x->ID); }, $results );
    $posts = get_posts( array(
        'numberposts' => -1,
        'post_type' => $post_type,
        'post__in' => $post_ids,
        'ignore_sticky_posts' => true,
        'orderby' => 'ID'
    ) );
    return $posts;
}

(Note: I didn't test this code directly. It came from code I wrote that's more specific to my project. If you find any obvious errors, please fix!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.