Trying to pass variable to WordPress function

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(); ?>

Related posts

Leave a Reply

2 comments

  1. 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(); and endforeach;. 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:

    $categories = get_the_category();
    $category   = $categories[0];
    
    $myposts = get_posts(array(
        'posts_per_page' => 5,
        'category'       => $category->cat_ID
    ));
    
    ?><ul><?php
    
    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
    
    endforeach;
    wp_reset_postdata();
    

    ?>

  2. Replace this:

    $myposts = get_posts('numberposts=5&category='.$the_category.'');
    

    with

    $myposts = get_posts('numberposts=5&category='.$the_category);
    

    Don’t use $post as a keyword in programming because $post is a reserved keyword for WordPress.