2

I need to echo products which have a discount between 20% to 40%. I tried using meta query but it is not comparing percentage rage. My Code :

<ul class="products">
    <?php

        $args = array(
            'post_type'      => 'product',
            'posts_per_page' => 4,
            'meta_query'     => array(
                    'relation' => 'BETWEEN',
                    array( // Simple products type
                        'key'           => '_sale_price',
                        'value'         => 0,
                        'compare'       => '>',
                        'type'          => 'numeric'
                    ),
                    array( // Simple products type
                        'key'           => '_sale_price',
                        'value'         => 1000,
                        'compare'       => '<',
                        'type'          => 'numeric'
                    )
                )
        );
        $loop = new WP_Query( $args );
        if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) : $loop->the_post();
                woocommerce_get_template_part( 'content', 'product' );
            endwhile;
        } else {
            echo __( 'No products found' );
        }
        wp_reset_postdata();
    ?>
</ul>

My code to get Discount Percentage :

global $product; 
$percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );

1 Answer 1

2

Do not change into "%" if it is not able to compare, but use 0.00 representation - 1.00 = 100% or 0.3 = 30%. It should do work :)

5
  • I tried it but it is not working, I tried changing type to DECIMAL and BINARY but it still not working.
    – wiseman
    Commented Feb 17, 2017 at 18:07
  • I don't see anywhere appropriate loop condition about which You say that there should be. Commented Feb 17, 2017 at 18:09
  • meta_query 'type' => 'numeric'
    – wiseman
    Commented Feb 17, 2017 at 18:15
  • WP Codex says that possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS' (only in WP >= 3.5), and 'NOT EXISTS' (also only in WP >= 3.5). I think that there should be =< not =>. Commented Feb 17, 2017 at 19:01
  • Can you please post the full code which i should use ?
    – wiseman
    Commented Feb 17, 2017 at 19:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.