admin管理员组

文章数量:1122846

I have this code for show count of posts by category.

If I visit category sports, show in header 34 articles. If I visit Nutrition Category show in header 12 articles.

But this code is wrong, anyone know why?

add_shortcode('catcount', 'wp_get_cat_postcount');
function wp_get_cat_postcount($id) {
    $cat= get_the_category();
    echo '<span class="catcount">'. $cat[0]->count .' ARTÍCULOS</span>';
}

I have this code for show count of posts by category.

If I visit category sports, show in header 34 articles. If I visit Nutrition Category show in header 12 articles.

But this code is wrong, anyone know why?

add_shortcode('catcount', 'wp_get_cat_postcount');
function wp_get_cat_postcount($id) {
    $cat= get_the_category();
    echo '<span class="catcount">'. $cat[0]->count .' ARTÍCULOS</span>';
}
Share Improve this question edited Feb 27, 2019 at 9:41 Krzysiek Dróżdż 25.5k9 gold badges53 silver badges74 bronze badges asked Feb 27, 2019 at 9:30 En Código WPEn Código WP 213 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

OK, so the code is wrong, because there are a lot of errors in it:

  1. Shortcodes should return its results and they shouldn't print anything.
  2. Shortcode callback takes an array of attributes as first param and not an ID.
  3. You don't do anything with the parameter of your shortcode callback.
  4. You don't pass any ID to get_the_category, so it will return array of categories for current post.
  5. You don't check if there is any category assigned (get_the_category can return empty array).

get_the_category() gets the categories assigned to the 'current post', so there's several reasons this might not work in your case.

Firstly, the 'current post' isn't necessarily definitively set when you're using it outside The Loop.

Secondly, if the 'current post' (which is probably the first post on the current archive page) has multiple categories, then there's no guarantee that its first category ($cat[0]) will be the same category as the archive you're viewing.

If you want to get the number of posts in the category whose archive you're currently viewing, then use get_queried_object() to get that category:

function wpse_330091_get_cat_postcount() {
    if ( is_category() ) {
        $cat = get_queried_object();

        return '<span class="catcount">' . $cat->count . ' ARTÍCULOS</span>';
    }
}
add_shortcode( 'catcount', 'wpse_330091_get_cat_postcount' );

Also note:

  • I've checked is_category() first, so that we know for sure that the queried object will be a category.
  • Shortcodes need to return their output, not echo.
  • wp_ is a prefix used by WordPress, you should use your own prefix to avoid conflicts.

本文标签: categoriesdisplay number of posts by category Shortcode