2017-04-12 96 views
0

我想在Wordpress中爲Woocommerce產品設置一個自定義循環。我想在循環中顯示一個隨機特色產品。但由於某些原因,它沒有得到我的觀點,並從所有可用產品中隨機挑選產品。如何在WP自定義循環中顯示隨機特色產品(woocommerce)?

這是我在使用的代碼。它確實顯示了一個隨機產品,但它忽略了代碼的特色部分。

$args = array(
    'posts_per_page' => 1, 
    'orderby'   => 'rand', 
    'post_type'  => 'product', 
    'meta_query' => array(
     'key'  => '_featured', 
     'value' => 'yes' 
    ) 
); 

$loop = new WP_Query($args); 
while ($loop->have_posts()) : $loop->the_post(); global $product; ?> 

<li> 
    <a href="<?php echo the_permalink(); ?>"> 
     <h3><?php the_title(); ?></h3> 
    </a> 
</li> 

<?php endwhile; 
wp_reset_query(); ?> 

有人能讓我走向正確的方向嗎?

在此先感謝!

回答

3

我剛剛碰到這個,

它不是直接針對您的問題,但可能是它的基礎。

它似乎特色項目不再存儲爲元:

$meta_query = WC()->query->get_meta_query(); 
    $tax_query = WC()->query->get_tax_query(); 
    $tax_query[] = array(
     'taxonomy' => 'product_visibility', 
     'field' => 'name', 
     'terms' => 'featured', 
     'operator' => 'IN', 
    ); 

$query_args = array(
    'post_type'   => 'product', 
    'post_status'   => 'publish', 
    'ignore_sticky_posts' => 1, 
    'posts_per_page'  => 1, 
    'meta_query'   => $meta_query, 
    'tax_query'   => $tax_query, 
);` 
+0

非常感謝。這是解決方案。它正在工作! 我已將'orderby'=>'rand'添加到$ query_args,所以它隨機顯示了一個特色產品。 – Borneyak

+0

適用於woocommerce 3.x - 具備以下特色產品的功能會很好:'wc_get_product_ids_on_sale()' –

0

我覺得你的鍵值數組是太遠了在預期陣列層次,試試這個:

$args = array(
    'posts_per_page' => 1, 
    'orderby'   => 'rand', 
    'post_type'  => 'product', 
    'meta_query' => array(
     array(
      'key'  => '_featured', 
      'value' => 'yes', 
     ) 
    ) 
); 
+0

想這一點,但沒有奏效。我嘗試了另一種方式,把數組放在一層,而不是數組中的一層。那也行不通。也嘗試了'meta_key'=>'_featured'這個參數。也沒有工作。 – Borneyak

+0

我希望有人對我有一個答案。我還在尋找...... – Borneyak

0

我得到了同樣的問題。嘗試這個 !對我的作品

<?php 
     $featured_query = new WP_Query(array(
      'tax_query' => array(
        array(
        'taxonomy' => 'product_visibility', 
        'field' => 'name', 
        'terms' => 'featured', 
        'operator' => 'IN' 
       ), 
     ), 
    )); 
?> 
1

特色產品循環中WooCommerce 3

<ul class="products"> 
<?php 
    $args = array(
     'post_type'  => 'product', 
     'posts_per_page' => 12, 
     'orderby'  => 'rand', 
     'tax_query' => array(
       array(
        'taxonomy' => 'product_visibility', 
        'field' => 'name', 
        'terms' => 'featured', 
       ), 
      ), 
     ); 
    $loop = new WP_Query($args); 
    if ($loop->have_posts()) { 
     while ($loop->have_posts()) : $loop->the_post(); 
      wc_get_template_part('content', 'product'); 
     endwhile; 
    } else { 
     echo __('No products found'); 
    } 
    wp_reset_postdata(); 
?> 
相關問題