Jump to content

How to get the total number of posts in a category with a certain tag in Wordpress?


Anders2
 Share

Recommended Posts

I use this code in functions.php

 

// recent posts shortcode/
// @ https://digwp.com/2018/08/shortcode-display-recent-posts/
function shapeSpace_recent_posts_shortcode($atts, $content = null) {
    
    global $post;
    
    extract(shortcode_atts(array(
        'cat'     => '',
        'num'     => '5',
        'order'   => 'DESC',
        'orderby' => 'post_date',
        'offset'  => '',
    ), $atts));
    
    $args = array(
        'cat'            => $cat,
        'posts_per_page' => $num,
        'order'          => $order,
        'orderby'        => $orderby,
        'offset'         => $offset,
    );
    
    $output = '';
    
    $posts = get_posts($args);
    
    foreach($posts as $post) {
        
        setup_postdata($post);
        
        $output .= the_tags() .'';
        
    }
    
    wp_reset_postdata();
    
    return ''. $output .'';
    
}
add_shortcode('recent_posts', 'shapeSpace_recent_posts_shortcode');

 

When I then use this shortcode: [recent_posts num="1" offset="0" cat="39"]

then I get the category name with a link to /tag/categoryname/

How do I modify the (bold line of) code so that I also get the total number of posts with this tag in this category, like this: uncategorized (5)

Something like this?

$output .= the_tags() .' <strong>('. count($a_variable) .')</strong>';

 

Thanks in advance

Anders

Link to comment
Share on other sites

Hi!
The problem is solved.

All I did was add:
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo ' <strong>('. $tag->count .')</strong>';
}
}

directly after:
$output .= the_tags() .'';

I found the solution here (under "More Information"):
https://developer.wordpress.org/reference/functions/get_the_tags/
I got to change from $tag->name to $tag->count

Greetings
Anders

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.