最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Undefined $post in wp_query

programmeradmin4浏览0评论

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:

<?php

$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 }

        wp_reset_postdata();
    }

?>

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

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:

<?php

$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 }

        wp_reset_postdata();
    }

?>

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

Share Improve this question asked Jul 31, 2019 at 9:44 FreddyFreddy 1671 silver badge12 bronze badges 2
  • 1 Try global $post; ? – Sally CJ Commented Jul 31, 2019 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 Commented Jul 31, 2019 at 10:22
Add a comment  | 

1 Answer 1

Reset to default 1

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() ) {
    return;
}

$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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论