I have a custom post type called resources. On it's post template, I have a widget which will display posts which have the same tags, i.e. If I'm on an article post, the widget will show other articles. To do this, I have the following query:


$args = array(
    'post_type' => 'resources',
    'category__in'   => wp_get_post_categories($post->ID ),
    'posts_per_page' => 3,
    'post__not_in'   => array($post->ID )
$relatedPosts = new WP_Query( $args );

     if( $relatedPosts->have_posts() ) { 

        while( $relatedPosts->have_posts() ) {
            $relatedPosts->the_post(); ?>

            <div class="content">test</div>

        <?php }



But receiving Undefined variable: post errors. How do I avoid getting this error?

  • 1
    Try global $post; ? – Sally CJ Jul 31 at 10:06
  • You are using the $post variable, which is to contain the data of the current post. But to be able to use it (eg. in a function) you have to add first global $post;. – nmr Jul 31 at 10:22

The most reliable way to get the current post being viewed is not the global $post variable. Instead you should first check is_singular(), and then use get_queried_object() to get the post object, or get_queried_object_id() to just get the ID.

if ( ! is_singular() ) {

$post_id = get_queried_object_id();

$args = array(
    'post_type'      => 'resources',
    'category__in'   => wp_get_post_categories( $post_id ),
    'posts_per_page' => 3,
    'post__not_in'   => array( $post_id )

// etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.