2017-04-12 106 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(); 
?> 
相关问题