get_page_by_title() deprecated

In WordPress 6.2, the get_page_by_title() function has been deprecated in favour of using WP_Query (#57041). Unlike the deprecated function, WP_Query can only be run after plugins and pluggable functions have loaded, on the plugins_loaded action or later.

Due to limitations with the deprecated functions database query, it could return different results depending on the database version and/or engine used. Switching to WP_Query will ensure you receive the same results regardless of the setup of your server.

To achieve an equivalent database query via WP_Query, the following arguments can be used.

$query = new WP_Query(
	array(
		'post_type'              => 'page',
		'title'                  => 'Sample Page',
		'post_status'            => 'all',
		'posts_per_page'         => 1,
		'no_found_rows'          => true,
		'ignore_sticky_posts'    => true,
		'update_post_term_cache' => false,
		'update_post_meta_cache' => false,
		'orderby'                => 'post_date ID',
		'order'                  => 'ASC',
	)
);

if ( ! empty( $query->post ) ) {
	$page_got_by_title = $query->post;
} else {
	$page_got_by_title = null;
}

The same result can also be achieved via the get_posts() wrapper for WP_Query(). In this case, you can replace the code with the following:

$posts = get_posts(
	array(
		'post_type'              => 'page',
		'title'                  => 'Sample Page',
		'post_status'            => 'all',
		'numberposts'            => 1,
		'update_post_term_cache' => false,
		'update_post_meta_cache' => false,			
		'orderby'                => 'post_date ID',
		'order'                  => 'ASC',
	)
);

if ( ! empty( $posts ) ) {
	$page_got_by_title = $posts[0];
} else {
	$page_got_by_title = null;
}

Ensuring the page is accessible

Due to the database query used by get_page_by_title(), it was possible the result returned from the database was not intended to be accessible by the user and that linking to the result would lead to a File Not Found error.

The code above reproduces this behaviour. If you wish to avoid this edge, then leave the post_status parameter out of the code above will resolve your issue.

Props to @afragen@spacedmonkey, @milana_cap, @bph@webcommsat for proofreading.

#6-2, #dev-notes