get_page_by_title() WordPress Function

The get_page_by_title() function is used to retrieve a page object from the database by its title. This function is useful for retrieving a page by its slug (e.g. my-page) or by its ID (e.g. 123).

get_page_by_title( string $page_title, string $output = OBJECT, string|array $post_type = 'page' ) #

Retrieve 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.


Top ↑

Parameters

$page_title

(string)(Required)Page title.

$output

(string)(Optional) 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 value: OBJECT

$post_type

(string|array)(Optional) Post type or array of post types.

Default value: 'page'


Top ↑

Return

(WP_Post|array|null) WP_Post (or array) on success, or null on failure.


Top ↑

Source

File: wp-includes/post.php

function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) {
	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;
}


Top ↑

Changelog

Changelog
VersionDescription
3.0.0The $post_type parameter was added.
2.1.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More