Make WordPress Core

Changeset 54234

Timestamp:
09/20/2022 01:13:51 AM (23 months ago)
Author:
peterwilsoncc
Message:

Posts, Post types: Cache get_page_by_title().

Convert get_page_by_title() to a WP_Query wrapper to take advantage of the object caching built in to the latter.

Add dedicated unit tests for the function get_page_by_title().

Props spacedmonkey, boonebgorges, igmoweb, pcfreak30, pbearne.
Fixes #36905.

Location:
trunk
Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/post.php

    r54126 r54234  
    57575757 * @since 3.0.0 The `$post_type` parameter was added.
    57585758 *
    5759  * @global wpdb $wpdb WordPress database abstraction object.
    5760  *
    57615759 * @param string       $page_title Page title.
    57625760 * @param string       $output     Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
     
    57675765 */
    57685766function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) {
    5769     global $wpdb;
    5770 
    5771     if ( is_array( $post_type ) ) {
    5772         $post_type           = esc_sql( $post_type );
    5773         $post_type_in_string = "'" . implode( "','", $post_type ) . "'";
    5774         $sql                 = $wpdb->prepare(
    5775             "
    5776             SELECT ID
    5777             FROM $wpdb->posts
    5778             WHERE post_title = %s
    5779             AND post_type IN ($post_type_in_string)
    5780         ",
    5781             $page_title
    5782         );
    5783     } else {
    5784         $sql = $wpdb->prepare(
    5785             "
    5786             SELECT ID
    5787             FROM $wpdb->posts
    5788             WHERE post_title = %s
    5789             AND post_type = %s
    5790         ",
    5791             $page_title,
    5792             $post_type
    5793         );
    5794     }
    5795 
    5796     $page = $wpdb->get_var( $sql );
    5797 
    5798     if ( $page ) {
    5799         return get_post( $page, $output );
    5800     }
    5801 
    5802     return null;
     5767    $args  = array(
     5768        'post_title'             => $page_title,
     5769        'post_type'              => $post_type,
     5770        'post_status'            => get_post_stati(),
     5771        'posts_per_page'         => 1,
     5772        'update_post_term_cache' => false,
     5773        'update_post_meta_cache' => false,
     5774        'no_found_rows'          => true,
     5775        'orderby'                => 'ID',
     5776        'order'                  => 'ASC',
     5777    );
     5778    $query = new WP_Query( $args );
     5779    $pages = $query->get_posts();
     5780
     5781    if ( empty( $pages ) ) {
     5782        return null;
     5783    }
     5784
     5785    return get_post( $pages[0], $output );
    58035786}
    58045787
Note: See TracChangeset for help on using the changeset viewer.