Should we trust the post globals?

There is a sad truth: you can never ever be sure that some code will not break your code, and there is nothing you can do to prevent that. Especially in WordPress, where everything is global.

That said, yes, global $post is one of the most used global var, so using special care for it can be a good idea.

In my code I rarely directly access global $post.

When in singular contest, I use get_queried_object() and usually check if $post is a valid WP_Post instance:

$post = get_queried_object();

if ( ! $post instanceof \WP_Post ) {
   die( 'What the f**k?!' );
}

I do that check also in the rare cases I access $post directly.

Consider that get_queried_object() returns an unexpected value if some code uses query_posts, but hey, if someone uses code that relies on query_posts, they deserve it if their site breaks 🙂

Moreover, if I expect some conditions, I check for them, e.g. specific post types or a specific status.

If I need more checks and in more places, I create a function to perform them:

function get_global_post() {
    global $post;
    if ( 
        ! $post instanceof \WP_Post
        || ! $post->post_type === 'mycpt'
        || ! in_array( $post->post_status, array( 'publish', 'private' ), true ) 
    ) {
        return false;
    }
    return $post;
}

$mypost = get_global_post();

if ( ! $mypost ) {
      die( 'What the f**k?!' );
}

When inside a custom query, while looping, calling the_post() resets the post object, so it should be fine. Then it’s my responsibility to call wp_reset_postdata() after a custom query, and I do that, of course 🙂

Leave a Comment