Make WordPress Core


Ignore:
Timestamp:
03/20/2019 03:48:46 PM (6 years ago)
Author:
boonebgorges
Message:

Posts: Avoid the use of globals in get_the_content() and related functions.

This changeset introduces $post parameters to get_the_content() and
wp_trim_excerpt(). When a $post object is passed to one of these functions,
the functions will operate on the data from that object, rather than from the
post globals ($authordata, $page, etc). This ensures that the functions work
in a predictable manner when used outside of the regular post loop.

The global-mismatch problem is surfaced in cases where get_the_excerpt() is
called outside of the post loop, on posts that don't have a defined excerpt. In
these cases, the post globals - used to generate a fallback excerpt - may refer
to the incorrect object, resulting in PHP notices or other unpredictable
behavior. See #36934 for a related issue.

Props spacedmonkey, kraftbj, Shital Patel.
Fixes #42814.

File:
1 edited

Legend:

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

    r43571 r44941  
    11121112    return false;
    11131113}
     1114
     1115/**
     1116 * Generates post data.
     1117 *
     1118 * @since 5.2.0
     1119 *
     1120 * @global WP_Query $wp_query Global WP_Query instance.
     1121 *
     1122 * @param WP_Post|object|int $post WP_Post instance or Post ID/object.
     1123 * @return array|bool Elements of post, or false on failure.
     1124 */
     1125function generate_postdata( $post ) {
     1126    global $wp_query;
     1127
     1128    if ( ! empty( $wp_query ) && $wp_query instanceof WP_Query ) {
     1129        return $wp_query->generate_postdata( $post );
     1130    }
     1131
     1132    return false;
     1133}
Note: See TracChangeset for help on using the changeset viewer.