: str_replace(): Passing null to parameter #2 ($replace) of type array|string is deprecated in
* Provide utilities to interact and replace the current post akin to setup_postdata()
* but in a stacking manner.
protected static $stack = array();
* Get the top post from the stack or the current one if the stack is empty.
* @param integer $offset Offset from the end of the array, 0 being the last post. Use negative integers.
public static function get( $offset = 0 ) {
$index = count( self::$stack ) - 1 + $offset;
if ( empty( self::$stack ) && 0 === $index ) {
return isset( self::$stack[ $index ] ) ? self::$stack[ $index ] : null;
* Pop the top post off of the stack.
public static function pop() {
array_pop( self::$stack );
* Setup a post as the global $post.
* @param WP_Post|null $with
protected static function setup( $with, $force = false ) {
if ( $force || ! ( $with && $post && $with->ID === $post->ID ) ) {
* Equivalent to setup_postdata() but keeps a stack of posts so it can be nested.
* Pushes the specified post on the stack.
public static function replace( $with ) {
$force = empty( self::$stack );
if ( empty( self::$stack ) ) {
// Add the current post as the first in the stack even if it does not exist.
self::setup( $with, $force );
* Restores the last post from the stack.
* The final restore will setup the post that was setup when the stack was last empty.
public static function restore() {
* Resets the post to the one at the top of the stack.
public static function reset() {
if ( ! empty( self::$stack ) ) {
self::setup( self::get() );
* Returns the $post for the current true WordPress query post ignoring any posts that may be
* forced using setup_postdata().
public static function get_main_post() {
if ( ! $wp_query || 0 === $wp_query->post_count ) {
// Handle special case where there is no current post but once the_content()
// gets called the global $post is polluted and will no longer reset to null.
if ( empty( $wp_query->post ) ) {
* Returns the post ID for the current true WordPress query post.
* See ::get_main_post() for more information.
public static function get_main_post_id() {
$post = self::get_main_post();
return $post ? (int) $post->ID : 0;