get_page_by_title

Retrieve a page given its title.

Description

(WP_Post|array|null) get_page_by_title( (string) $page_title, (constant) $output = OBJECT, (string) $post_type = 'page' ); 

Returns (WP_Post|array|null)

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

Parameters (3)

0. $page_title (string)
The page title.
1. $output — Optional. (constant) => OBJECT
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.
2. $post_type — Optional. (string) => 'page'
Post type or array of post types. Default page..

Usage

  1. if ( !function_exists( 'get_page_by_title' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // The page title. 
  5. $page_title = ''; 
  6.  
  7. // Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to 
  8. // a WP_Post object, an associative array, or a numeric array, respectively. Default OBJECT. 
  9. $output = OBJECT; 
  10.  
  11. // Optional. Post type or array of post types. Default 'page'. 
  12. $post_type = 'page'; 
  13.  
  14. // NOTICE! Understand what this does before running. 
  15. $result = get_page_by_title($page_title, $output, $post_type); 
  16.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/post.php  
  1. function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) { 
  2. global $wpdb; 
  3.  
  4. if ( is_array( $post_type ) ) { 
  5. $post_type = esc_sql( $post_type ); 
  6. $post_type_in_string = "'" . implode( "', '", $post_type ) . "'"; 
  7. $sql = $wpdb->prepare( " 
  8. SELECT ID 
  9. FROM $wpdb->posts 
  10. WHERE post_title = %s 
  11. AND post_type IN ($post_type_in_string) 
  12. ", $page_title ); 
  13. } else { 
  14. $sql = $wpdb->prepare( " 
  15. SELECT ID 
  16. FROM $wpdb->posts 
  17. WHERE post_title = %s 
  18. AND post_type = %s 
  19. ", $page_title, $post_type ); 
  20.  
  21. $page = $wpdb->get_var( $sql ); 
  22.  
  23. if ( $page ) { 
  24. return get_post( $page, $output );