skip to Main Content

I have a custom query inside my template, I want to show product by price, I want to query free products, and only show $0 products on my home page.

2

Answers


  1. Add this to your theme functions.php, and let me know If it works.

    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 );
    }
    

    If you want to display on your homepage the products add this code:

    <?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; ?>
    
    Login or Signup to reply.
  2. $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 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search