Chandrakant
Chandrakant

Reputation: 111

WordPress - Display categories only if post count greater than / equal to 3

I am struggling with this code to display categories (with posts) only if posts in that category are greater than / equal to 3.

I am using WP_Query with args() to get the categories and display latest 3 posts from those categories.

Any help will be highly appreciated.

<?php
$categories = get_categories( $args );
foreach( $categories as $category ) { 
$args = array(
'cat' => $category->term_id,
'posts_per_page' => 3,
'post_type' => 'post',
);
$terms = get_terms(array(
'taxonomy' => 'category'
) );
foreach($terms as $term) {
if($term->count >= 3) {
echo $term->name;
$the_query = new WP_Query( $args );
echo '<h3>' . $category->name . '</h3>'; // Display category name
while ( $the_query->have_posts() ) : $the_query->the_post();
?>
<h3>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h3>
<h3>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>
</a>
</h3>
<?php
endwhile;
}
}
} 
wp_reset_postdata();
?>

Upvotes: 2

Views: 1446

Answers (1)

Fresz
Fresz

Reputation: 1913

The WP_Query will return posts for a specific category and not categories themself.

You need to grab all of the categories and loop through them and check the count.

https://developer.wordpress.org/reference/functions/get_terms/

It should be something like this: (untested!)

$terms = get_terms(array(
    'taxonomy' => 'category'
) );

foreach($terms as $term) {
  if($term->count >= 3) {

    echo $term->name;

  }
}

$categories = get_terms( array(
    'taxonomy' => 'category',
    'hide_empty' => false,
));

foreach ($categories as $category) {

    $args = array(
        'cat' => $category->term_id,
        'posts_per_page' => -1,
        'post_type' => 'post'
    );
    
    if ($category->count >= 3) {
        echo $category->name;
        $the_query = new WP_Query($args);
        echo '<h3>' . $category->name . '</h3>'; // Display category name
        while ($the_query->have_posts()) : $the_query->the_post();
?>
            <h3>
                <a href="<?php the_permalink(); ?>">
                    <?php the_title(); ?>
                </a>
            </h3>
            <h3>
                <a href="<?php the_permalink(); ?>">
                    <?php the_post_thumbnail(); ?>
                </a>
            </h3>
<?php
        endwhile;
    }
}

wp_reset_postdata();

get_terms() array can take in a lot of arguments so please check the documentation first.

Let me know if you have any problems with it. I'll try to help :)

Upvotes: 2

Related Questions