Woocommerce在商店和类别上方显示特色商品和隐藏商品

时间:2020-04-02 18:04:28

标签: php wordpress woocommerce

我需要在商店和类别页面的循环上方显示特色产品。我能够做到这一点,但我还需要将这些产品隐藏在默认循环中。 我想通过产品可见性设置来解决此问题,但始终在两个循环中都显示或隐藏产品。

理想情况下,我想将产品设置为特色商品和隐藏商品,并设置自定义循环以忽略可见性设置。我只是想不通。

我当前正在使用此代码:

function featured_products_beforeloop() {
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => 12,
        'tax_query' => array(
            array(
                'field'    => 'name',
                'terms'    => 'featured',
            ),
        ),
    );

    $loop = new WP_Query( $args ); ?>
    <ul class="products columns-<?php echo esc_attr( wc_get_loop_prop( 'columns' ) ); ?>">
        <?php while ( $loop->have_posts() ) : 
        global $product; ?>
            <li <?php wc_product_class( '', $product ); ?>>  
            <?php  if ( has_post_thumbnail( $loop->post->ID ) ) 
                echo get_the_post_thumbnail( $loop->post->ID, 'shop_catalog' ); 
            else 
                echo '<img src="' . woocommerce_placeholder_img_src() . '" alt="' . $product->get_title() . '" class="attachment-shop_catalog size-shop_catalog wp-post-image" width="300px" height="300px" />'; ?>
            <h3><?php the_title(); ?></h3>

            <?php if ( $price_html = $product->get_price_html() ) : ?>
            <span class="price"><?php echo $price_html; ?></span>
            <?php endif;
            woocommerce_template_loop_add_to_cart( $loop->post, $product ); ?>    
        </li>
        <?php 
    endwhile; ?>
</ul> <?php
    wp_reset_postdata();    
} 

add_action( 'woocommerce_before_shop_loop', 'featured_products_beforeloop', 10 );

1 个答案:

答案 0 :(得分:0)

您尝试过吗:

$args = array(
    'post_type' => 'product',
    'posts_per_page' => 12,

    'tax_query' => array(
        array(
            'taxonomy' => 'product_visibility',
            'field'    => 'name',
            'terms'    => 'featured',
        ),
        // allow both hidden and not hidden featured items
        array(
            'relation' => 'OR',
            array(
                'taxonomy' => 'product_visibility',
                'field'    => 'name',
                'terms'    => 'hidden',
                'operator' => 'NOT IN',
            ),
            array(
                'taxonomy' => 'product_visibility',
                'field'    => 'name',
                'terms'    => 'hidden',
                'operator' => '=',
            ),
        )
    ),
);