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?
1 Answer
Reset to default 1The 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.
global $post;
? – Sally CJ Commented Jul 31, 2019 at 10:06$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 firstglobal $post;
. – nmr Commented Jul 31, 2019 at 10:22