[英]Combining Wordpress multiple shortcodes
我創建了四個簡碼代碼片段,以顯示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 );
} );
是的,它有可能。 由於您的后三個簡碼非常相似(只是'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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.