Retrieves a page given its title.
Description
If more than one post uses the same title, the post with the smallest ID will be returned.
Be careful: in case of more than one post having the same title, it will check the oldest publication date, not the smallest ID.
Because this function uses the MySQL ‘=’ comparison, $page_title will usually be matched as case-insensitive with default collation.
Parameters
$page_title
stringrequired- Page title.
$output
stringoptional- The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a WP_Post object, an associative array, or a numeric array, respectively.
Default:
OBJECT
$post_type
string|arrayoptional- Post type or array of post types. Default
'page'
.Default:
'page'
Source
function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) {
_deprecated_function( __FUNCTION__, '6.2.0', 'WP_Query' );
global $wpdb;
if ( is_array( $post_type ) ) {
$post_type = esc_sql( $post_type );
$post_type_in_string = "'" . implode( "','", $post_type ) . "'";
$sql = $wpdb->prepare(
"SELECT ID
FROM $wpdb->posts
WHERE post_title = %s
AND post_type IN ($post_type_in_string)",
$page_title
);
} else {
$sql = $wpdb->prepare(
"SELECT ID
FROM $wpdb->posts
WHERE post_title = %s
AND post_type = %s",
$page_title,
$post_type
);
}
$page = $wpdb->get_var( $sql );
if ( $page ) {
return get_post( $page, $output );
}
return null;
}
Deprecated !!!
Here’s the link to the deprecation info article: https://make.wordpress.org/core/2023/03/06/get_page_by_title-deprecated/
In a nutshell:
Peter Wilson recommends the following alternative:
Or, alternatively, you can use the
new WP_Query()
method as well.How To Find WordPress Page ID By Title Then Replace the_content()
In this example, we find the page id of “Sample Page” then replace the page’s the_content() with “Hello World!”
How to Find WordPress Custom Post Type by Title
This is useful for Custom Post Types. Below, we find the $post array of a Custom Post Type “link” with a title of “World Peace Now”:
This comment was copied from Codex.
It is very important to mention that the function will disregard any post_status so if it finds and old post that is draft, it will show that result. So if you need to filter by post status you better build your own query.
Find Page ID to use with exclude in wp_list_pages
This example will return the $page object for the page titled “About”. Then the $page->ID element is used to exclude the About page when listing pages.