我想显示标题中的项目计数,当前类别中的项目计数。。。
示例:用户转到;T恤衫“&燃气轮机;在标题中,它说;20项他们前往;连帽衫“&燃气轮机;标题上写着;10项“;
我目前正在函数中使用一个短代码和代码。php:
add_shortcode( \'products-counter\', \'products_counter\' );
function products_counter( $atts ) {
$atts = shortcode_atts( [
\'category\' => \'\',
], $atts );
$taxonomy = \'product_cat\';
if ( is_numeric( $atts[\'category\'] ) ) {
$cat = get_term( $atts[\'category\'], $taxonomy );
} else {
$cat = get_term_by( \'slug\', $atts[\'category\'], $taxonomy );
}
if ( $cat && ! is_wp_error( $cat ) ) {
return $cat->count;
}
return \'\';
}
如果我在短代码中定义产品类别,这将非常有用。。。我的问题是它在标题中,所以所有分类页面都显示相同的项目计数。。。有没有办法让它基于url显示?
SO网友:Baikare Sandeep
您需要添加产品类别页面上的挂钩,而不是添加快捷码:
// Use this hook for working directly on category page
// add_action( \'woocommerce_archive_description\', \'show_category_product_counts\', 10 );
// Use this shortcode hook if you want to put on anywhere in the category page if you are using Elementor/WPBakery
add_shortcode( \'product_cat_count\', \'show_category_product_counts\', 10);
function show_category_product_counts( ) {
// Return if it is product archive/Shop page
if( !is_product_category())
return false;
// Get product category object
$category = get_queried_object();
$categoryId = $category->term_id;
$term = get_term( $categoryId, \'product_cat\' );
echo \'Product Category: \'
. $term->name . \' (\'
. $term->count
. \' Items)\';
}
请将此代码添加到活动主题
function.php
文件它将在类别标题后的类别页面上显示产品类别计数。
注意:您可以在函数的最后一行进行更改以打印文本。
SO网友:HK89
将此代码放在标题上,并检查它是否正在处理标题
<?php
if (is_tax(\'product_cat\')) {
$category = get_queried_object();
$get_id = $category->term_id;
echo do_shortcode(\'[products_counter category="\'.$get_id.\'" ]\');
}
?>
功能。php
function products_counter( $atts ) {
$atts = shortcode_atts( [
\'category\' => \'\',
], $atts );
$taxonomy = \'product_cat\';
if ( is_numeric( $atts[\'category\'] ) ) {
$cat = get_term( $atts[\'category\'], $taxonomy );
} else {
$cat = get_term_by( \'slug\', $atts[\'category\'], $taxonomy );
}
if ( $cat && ! is_wp_error( $cat ) ) {
return $cat->count;
}
return \'\';
}
add_shortcode(\'products_counter\',\'products_counter\');