Make WordPress Core

Ticket #64362: 64362.diff

File 64362.diff, 1.6 KB (added by iflairwebtechnologies, 5 months ago)

Introduce pre_wp_post_get_instance filter to allow short-circuiting WP_Post creation for virtual/faux posts

  • src/wp-includes/class-wp-post.php

    # This patch adds the `pre_wp_post_get_instance` filter to WP_Post::get_instance().
    # Allows plugins/themes to provide faux post objects before database lookup.
    # Safe, backward-compatible, and recommended by Core standards.
    
    diff --git a/src/wp-includes/class-wp-post.php b/src/wp-includes/class-wp-post.php
    index 1db7a3a..9f36c57 100644
    a b class WP_Post { (this hunk was shorter than expected) 
    226226        public static function get_instance( $post_id ) {
    227227                global $wpdb;
    228228
     229                $post_id = (int) $post_id;
     230
     231                /**
     232                 * Filters the returned value for WP_Post::get_instance().
     233                 *
     234                 * Allows plugins and themes to provide their own faux or virtual WP_Post
     235                 * objects before WordPress attempts any database lookups.
     236                 *
     237                 * Returning a non-null value will short-circuit the default database query
     238                 * and return the provided object instead.
     239                 *
     240                 * @since 6.x.x
     241                 *
     242                 * @param WP_Post|object|null $pre      A custom/faux post object, or null to continue default behavior.
     243                 * @param int                 $post_id  The requested post ID.
     244                 */
     245                $pre = apply_filters( 'pre_wp_post_get_instance', null, $post_id );
     246
     247                if ( null !== $pre ) {
     248                        // Ensure result is a WP_Post object.
     249                        if ( $pre instanceof WP_Post ) {
     250                                return $pre;
     251                        }
     252
     253                        // Convert stdClass/array to WP_Post.
     254                        return new WP_Post( $pre );
     255                }
     256
     257                // If pre-filter did not override, continue with normal logic.
     258
    229259                $_post = wp_cache_get( $post_id, 'posts' );
    230260
    231261                if ( ! $_post ) {
    class WP_Post { 
    248279                }
    249280
    250281                return new WP_Post( $_post );
     282
    251283        }
    252284}