2017-04-24 127 views
1

我有这样的功能:与参数简码的动态呼叫

function test_q($atts){ 
    $args = shortcode_atts(array(
     'post_type' => 'product', 
        'columns' => 4, 
     'posts_per_page' => 12, 
        'tax_query' => array(
        'relation' => 'AND', 
        array(
         'taxonomy' => 'product_cat', 
         'field' => 'slug', 
         'terms' => array('mugs'), 
          ), 
        array(
         'taxonomy' => 'product_tag', 
         'field' => 'slug', 
         'terms' => array('football'), 
         ), 
        ), 
      ), $atts); 
    $loop = new WP_Query($args); 
    if ($loop->have_posts()) { 
        woocommerce_product_loop_start(); 
     while ($loop->have_posts()) : $loop->the_post(); 
      wc_get_template_part('content', 'product'); 
     endwhile; 
        woocommerce_product_loop_end(); 
    } else { 
     echo __('No products found'); 
    } 
      woocommerce_reset_loop(); 
    wp_reset_postdata(); 
    return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>'; 

} add_shortcode( 'testasd', 'test_q');

我想通过短代码将动态参数传递给'杯子'和'足球'。我按类别和标签过滤产品。这个函数工作正常,但我想通过简码将这两个参数传递给它,使其成为动态的。 我需要每次使用不同的“杯子”和“足球”来称呼这个简码。例如“T恤”和“篮球”。我将如何做到这一点?

回答

0

您可以通过提取短代码并通过短代码中的$ atts传递值来轻松完成。

你的论点之后,你可以通过它像下面,

if($args['tax_query']['taxonomy'] == 'product_cat'){ 
    $args['tax_query']['terms'] = $atts['terms_cat']; 
} 
if($args['tax_query']['taxonomy'] == 'product_tag'){ 
    $args['tax_query']['terms'] = $atts['terms_tag']; 
} 

然后在简码加2个参数,

[testasd terms_cat='t-shirts' terms_tag='basketball']