php - 结合 Wordpress 多个简码
问题描述
我创建了四个短代码片段来显示 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 );
} );
解决方案
是的,有可能。由于您的最后三个短代码非常相似(只是“条款”值更改),我们可以将其合并为一个……然后以下代码会将您的 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']
推荐阅读
- pivot-table - 在 Finicast 中,我无法将公式应用于数据透视表中的一组单元格
- php - Roundcube附件上传内部服务器错误
- amazon-web-services - 客户端到客户端的通信在 AWS Lightsail Debian Linux OpenVPN 服务器上不起作用
- pine-script - valuewhen() 没有提供正确的值
- python - 从 Python 中的其他文件导入函数
- java - RoomDB中的ManyToMany POJOS:如何获取按连接排序号排序的相关对象列表?
- javascript - 如何根据对象的特定值更新对象?
- amazon-dynamodb - DynamoDB 中全局二级索引 (GSI) 的最大非关键属性数是多少?
- react-native - React-native 导航,隐藏底部选项卡
- javascript - bootstrap-vue - 基于布尔值显示按钮