loop in single.php of the same category

by Dario B.   Last Updated July 12, 2019 07:08 AM

How can I put a loop in my single.php that shows the posts of the current category of the single and following the code structure that I have? The question comes, because I can not find the correct code.

I have tried with this code

<?php
 $categories = get_the_category($post->ID);
 if ( $categories ) {
 $category_ids = array();
 foreach ( $categories as $individual_category ) {
    $category_ids[] = $individual_category->term_id;
 }
$args=array(
    'category__in' => $category_ids,
    'post__not_in' => array($post->ID),
    'showposts'=>3, // Number of related posts that will be shown.
    'ignore_sticky_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {

    echo '<h3>Related Articles</h3>'; // You can edit this
    echo '<ul>';

    while ($my_query->have_posts()) {
        $my_query->the_post();
        ?>
        <!-- do stuff -->

        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

        <?php
    }

    echo '</ul>';

 }
}
?>

But as is obvious, this would only give me the category with ID number 3, and I need it to be the same as the single post that is being viewed.

Thanks

-EDIT-

This is my full single.php code

<div class="container">
<div id="breadcrumbs">
    <?php if (function_exists('nav_breadcrumb')) nav_breadcrumb(); ?>

</div>


<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

    <div class="single">
        <div class="columns is-centered">
            <div class="column is-two-fifths is-content">
                <?php the_post_thumbnail(); ?>
                <div class="title">
                    <?php the_title(); ?>
                </div>
            </div>
        </div>
    </div>
    <?php the_content(); ?>
<?php endwhile; endif; ?>

<hr/>

<?php
$categories = get_the_category($post->ID);
if ($categories) {
    $category_ids = array();
    foreach ($categories as $individual_category) {
        $category_ids[] = $individual_category->term_id;
    }
    $args = array(
        'category__in' => $category_ids,
        'post__not_in' => array($post->ID),
        'showposts' => 3, // Number of related posts that will be shown.
        'ignore_sticky_posts' => 1
    );
    $my_query = new wp_query($args);
    if ($my_query->have_posts()) {

        echo '<h3>Related Articles</h3>'; // You can edit this
        echo '<ul>';

        while ($my_query->have_posts()) {
            $my_query->the_post();
            ?>
            <!-- do stuff -->

            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

            <?php
        }

        echo '</ul>';

    }
}
?></div>


Related Questions


Updated March 16, 2017 17:08 PM

Updated September 03, 2016 08:05 AM

Updated May 12, 2017 05:08 AM

Updated January 07, 2017 08:03 AM

Updated December 09, 2018 06:08 AM