组合 Wordpress 多个短代码

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 文件。已测试并有效。

用法(对于它们中的每一个):

  1. 产品总数:[cmulti]
  2. 苹果:[cmulti term='254']
  3. 橘子:[cmulti term='256']
  4. 梨:[cmulti term='214']