2017-04-24 114 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']