如何通过$ 00产品的价格查询WooCommerce产品?

时间:2020-07-12 06:59:40

标签: jquery wordpress woocommerce wordpress-theming woocommerce-theming

我的模板中有一个自定义查询,我想按价格显示产品,我想查询免费产品,并且只在首页上显示$ 0个产品。

2 个答案:

答案 0 :(得分:1)

将此添加到您的主题functions.php中,让我知道它是否有效。

add_action( 'woocommerce_product_query', 'zero_price_products' );
function zero_price_products( $q ){
    $meta_query = $q->get( 'meta_query' );
        $meta_query[] = array(
        'key'       => '_price',
        'value'     => 0,
        'compare'   => '='
    );
    $q->set( 'meta_query', $meta_query );
}

如果要在首页上显示产品,请添加以下代码:

<?php
$args = array(
    'post_type' => 'product',
    'posts_per_page' => 8,
    'post_status' => 'publish',
    'orderby' => 'id',
    'order' => 'DESC',
    'meta_query' => array(
           array(
           'key'       => '_price',
           'compare'   => '=',
           'value'      => 0,
           )
        ),
);


$custom_posts = new WP_Query( $args );

if ($custom_posts->have_posts() ) : while ($custom_posts->have_posts() ) : $custom_posts->the_post(); ?>
    <?php
        wc_get_template_part( 'content', 'product' );
     ?>
<?php endwhile; endif; ?>

答案 1 :(得分:1)

$args = array(
            'post_type'      => 'product',
            'numberposts'      => -1,
            'meta_query'     => array(
                'relation' => 'OR',
                array(
                    'key'           => '_regular_price',
                    'compare' => 'NOT EXISTS'
                ),
                array( 
                    'key'           => '_price',
                    'compare' => 'NOT EXISTS'
                    
                ),
                array( 
                    'key'           => '_regular_price',
                    'compare' => '=',
                    'value' => 0,
                ),
                array( 
                    'key'           => '_price',
                    'compare' => '=',
                    'value' => 0,
                )
            )
        );
        
        $products =  get_posts( $args );