我创建了四个短代码段来显示woocommerce产品总数,以及我的三个父类别中每个类别的产品数。
它们起作用了,但是有一种方法可以将4个片段(总计,苹果,橘子,梨)组合成一个片段,从而允许简码中的变量表示要显示的产品数量?
// [title-total] shortcode
function total_product_count_shortcode( ) {
$count_posts = wp_count_posts( 'product' );
return esc_html($count_posts->publish);
}
add_shortcode( 'title-total', 'total_product_count_shortcode' );
// [title-apples] shortcode
add_shortcode( 'title-apples', function() {
$query = new WP_Query( array(
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => 254, // Replace with the parent category ID
'include_children' => true,
),
),
'nopaging' => true,
'fields' => 'ids',
) );
return esc_html( $query->post_count );
} );
// [title-oranges] shortcode
add_shortcode( 'title-oranges', function() {
$query = new WP_Query( array(
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => 256, // Replace with the parent category ID
'include_children' => true,
),
),
'nopaging' => true,
'fields' => 'ids',
) );
return esc_html( $query->post_count );
} );
// [title-pears] shortcode
add_shortcode( 'title-pears', function() {
$query = new WP_Query( array(
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => 214, // Replace with the parent category ID
'include_children' => true,
),
),
'nopaging' => true,
'fields' => 'ids',
) );
return esc_html( $query->post_count );
} );
答案 0 :(得分:0)
是可能的。由于您的最后三个简码非常相似(只是'terms'值的变化),我们可以将其合并为一个…然后下面的代码会将您的4个简码嵌入其中:
function custom_multi_shortcode( $atts, $content = null ) {
// Shortcode attributes
$atts = shortcode_atts(
array( 'term' => '' ),
$atts, 'cmulti'
);
// 1 - Total product count
if ( empty($atts['term']) ):
$count_posts = wp_count_posts( 'product' );
return esc_html($count_posts->publish);
// 2 to 4 - Apples, Oranges and Pears
else:
$query = new WP_Query( array(
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => (int) $atts['term'], // Replace with the parent category ID
'include_children' => true,
),
),
'nopaging' => true,
'fields' => 'ids',
) );
return esc_html( $query->post_count );
endif;
}
add_shortcode( 'cmulti', 'custom_multi_shortcode' );
代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。
用法(针对每个方法):
[cmulti]
[cmulti term='254']
[cmulti term='256']
[cmulti term='214']