Show posts assigned to multiple categories in current category page - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Sunday, November 19, 2023

Show posts assigned to multiple categories in current category page

I have the posts assigned to each category. However, some posts need to be assigned to multiple categories and this is when the code breaks. No error message whatsoever. Whenever I assign a post to multiple categories, the Wordpress website just loads posts from Cat1 only.

My post-assignment method:

Post1 - Cat1
Post2 - Cat2
Post3 - Cat1,Cat3,Cat4
Post4 - Cat3
Post5 - Cat4

Here's my code that works if each post is assigned to one single category. Once a post is assigned to multiple category, it fails. This is the code I have on category.php

<?php
    global $post;
    $category = get_the_category($post->ID);
    $category = $category[0]->cat_ID;
    $myposts = get_posts(
        array(
            'numberposts' => -1, 
            'offset' => 0, 
            'category__in' => array($category),
            'post_status'=>'publish',
            'order'=>'ASC' 
            )
        );
    foreach($myposts as $post) : setup_postdata($post);
?>
<a href="<?php the_permalink() ?>"><?php echo substr(get_the_title(),0,55); ?></a>
<?php endforeach; ?>
<?php wp_reset_query(); ?>


source https://stackoverflow.com/questions/77508154/show-posts-assigned-to-multiple-categories-in-current-category-page

No comments:

Post a Comment