如何在WP自定义循环中显示随机特色产品(woocommerce)?

问题描述 投票:0回答:4

我正在尝试在Wordpress中为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(); ?>

有人能引导我走向正确的方向吗?

提前致谢!

php wordpress loops woocommerce featured
4个回答
4
投票

我刚碰到这个,

它不是直接针对您的问题,而是可能是它的基础。

似乎特色商品不再存储为元:

    $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,
);`

2
投票

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();
?>

0
投票

我认为你的键值数组在预期的数组层次结构中太过分了,试试这个:

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

0
投票

我遇到了同样的问题。试试这个 !适合我

<?php
         $featured_query = new WP_Query( array(
             'tax_query' => array(
                     array(
                     'taxonomy' => 'product_visibility',
                     'field'    => 'name',
                     'terms'    => 'featured',
                     'operator' => 'IN'
                 ),
          ),
     ) );
?>
© www.soinside.com 2019 - 2024. All rights reserved.