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!)