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?
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');