Make WordPress Core

Changeset 59715


Ignore:
Timestamp:
01/27/2025 11:05:21 PM (3 months ago)
Author:
spacedmonkey
Message:

Revisions: Use WP_Query in wp_get_post_autosave.

Replaced the raw SQL query in the wp_get_post_autosave function with a WP_Query call. This change improves code maintainability and replaces the raw SQL query with a cacheable query via WP_Query.

Props narenin, swissspidy, mukesh27, spacedmonkey, im3dabasia1.
Fixes #62658.

Location:
trunk
Files:
1 added
1 edited

Legend:

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

    r58717 r59715  
    271271 * @since 2.6.0
    272272 *
    273  * @global wpdb $wpdb WordPress database abstraction object.
    274  *
    275273 * @param int $post_id The post ID.
    276274 * @param int $user_id Optional. The post author ID. Default 0.
     
    278276 */
    279277function wp_get_post_autosave( $post_id, $user_id = 0 ) {
    280     global $wpdb;
    281 
    282     $autosave_name = $post_id . '-autosave-v1';
    283     $user_id_query = ( 0 !== $user_id ) ? "AND post_author = $user_id" : null;
    284 
    285     // Construct the autosave query.
    286     $autosave_query = "
    287         SELECT *
    288         FROM $wpdb->posts
    289         WHERE post_parent = %d
    290         AND post_type = 'revision'
    291         AND post_status = 'inherit'
    292         AND post_name   = %s " . $user_id_query . '
    293         ORDER BY post_date DESC
    294         LIMIT 1';
    295 
    296     $autosave = $wpdb->get_results(
    297         $wpdb->prepare(
    298             $autosave_query,
    299             $post_id,
    300             $autosave_name
    301         )
     278    $args = array(
     279        'post_type'      => 'revision',
     280        'post_status'    => 'inherit',
     281        'post_parent'    => $post_id,
     282        'name'           => $post_id . '-autosave-v1',
     283        'posts_per_page' => 1,
     284        'orderby'        => 'date',
     285        'order'          => 'DESC',
     286        'fields'         => 'ids',
     287        'no_found_rows'  => true,
    302288    );
    303289
    304     if ( ! $autosave ) {
     290    if ( 0 !== $user_id ) {
     291        $args['author'] = $user_id;
     292    }
     293
     294    $query = new WP_Query( $args );
     295
     296    if ( ! $query->have_posts() ) {
    305297        return false;
    306298    }
    307299
    308     return get_post( $autosave[0] );
     300    return get_post( $query->posts[0] );
    309301}
    310302
Note: See TracChangeset for help on using the changeset viewer.