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
2 Answers
Reset to default 1OK, so the code is wrong, because there are a lot of errors in it:
- Shortcodes should return its results and they shouldn't print anything.
- Shortcode callback takes an array of attributes as first param and not an ID.
- You don't do anything with the parameter of your shortcode callback.
- You don't pass any ID to get_the_category, so it will return array of categories for current post.
- 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, notecho
. wp_
is a prefix used by WordPress, you should use your own prefix to avoid conflicts.
本文标签: categoriesdisplay number of posts by category Shortcode
版权声明:本文标题:categories - display number of posts by category Shortcode 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736304644a1932307.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论