Hello my fellow developers. I’m attempting to modify a secondary WordPress query and have it display a list of posts according to the parent posts category. Currently it does output the html to style the post, however it is not according to the category. What am I missing here? Thanks in advance.
<?php
$the_category = get_the_category($post->ID);
global $post;
$myposts = get_posts('numberposts=5&category='.$the_category.'');
foreach($myposts as $post) : setup_postdata($post); ?>
<li>
<div class="suggestVid">
<span style="padding-right:5px; float:left;">
<?php the_post_thumbnail('suggest-vid'); ?></span>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
</div>
</li>
<?php wp_reset_postdata(); ?>
<?php endforeach; ?>
<?php wp_reset_query(); ?>
You are calling
get_the_category($post->ID);
and thinking it just returns a category, when it actually returns an array of category objects. Assuming each post only has one category, you can just take the first result that was returned.You also mixed up the order of
wp_reset_postdata();
andendforeach;
. You end up resetting the post data inside your loop so it’s always resetting back to the current page through every loop iteration. You only want to reset it once the loop is finished.Also, if you are inside The Loop, like say, on a template page, you don’t have to specify
global $post;
directly.Try this:
?>
Replace this:
with
Don’t use
$post
as a keyword in programming because$post
is a reserved keyword for WordPress.