WordPress函数get_page_by_title()通过页面的标题获取页面信息

描述:

通过页面的标题获取页面信息

用法:

<?php  get_page_by_title( $page_title, $output, $post_type );?>

参数:

$page_title

(string) (必填) 页面标题

默认值: None

$output

(string) (可选) 输出类型. OBJECTARRAY_N, or ARRAY_A.

默认值: OBJECT

$post_type

(string) (可选) 自定义文章类型

默认值: page

示例:

<?php 
$page = get_page_by_title( 'About' );
wp_list_pages( 'exclude=' . $page->ID );
?>

源文件:

/**
 * Retrieve a page given its title.
 *
 * @since 2.1.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param string       $page_title Page title
 * @param string       $output     Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
 *                                 Default OBJECT.
 * @param string|array $post_type  Optional. Post type or array of post types. Default 'page'.
 * @return WP_Post|array|void WP_Post on success or null on failure
 */
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 );
	}
}