首页 > 解决方案 > 结合 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 );
} );

标签: phpwordpresswoocommercecountshortcode

解决方案


是的,有可能。由于您的最后三个短代码非常相似(只是“条款”值更改),我们可以将其合并为一个……然后以下代码会将您的 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']

推荐阅读