post = $post; $query->reset_postdata(); } /** Puts back the post that was current before set(); when there was none, there is none again. */ public static function restore(?\WP_Post $previous): void { if ($previous instanceof \WP_Post) { self::set($previous); return; } unset($GLOBALS['post']); // the request had no current post (REST, 404 …): do not leave ours behind } /** * Runs $callback with $post as the current post, then restores the previous one. * * @template T * @param callable(): T $callback * @return T */ public static function with($post, callable $callback) { if (!$post instanceof \WP_Post) { return $callback(); } $previous = self::current(); self::set($post); try { return $callback(); } finally { self::restore($previous); } } }