Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

php - Display on a page all products below a specific price in Woocommerce

I have a Woocommerce store with more than 1000 products. I would like that all products which have a price below 999 should be shown on a separate page, so I can tag that Page in my menu.

Is it possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update: (added 'type' => 'DECIMAL', to the meta_query array)

This can be done using Woocommerce shortcode [products] to be used on a page, with the following additional code (that will add the possibility to define a price to be compared through an existing argument):

add_filter( 'woocommerce_shortcode_products_query', 'products_based_on_price', 10, 3 );
function products_based_on_price( $query_args, $atts, $loop_name ) {
    if( ! ( isset($atts['class']) && ! empty($atts['class']) ) )
        return $query_args;

    if (strpos($atts['class'], 'below-') !== false) {
        $compare   = '<';
        $slug    = 'below-';
    } elseif (strpos($atts['class'], 'above-') !== false) {
        $compare   = '<';
        $slug    = 'above-';
    }

    if( isset($compare) ) {
        $query_args['meta_query'][] = array(
            'key'     => '_price',
            'value'   => (float) str_replace($slug, '', $atts['class']),
            'type'    => 'DECIMAL',
            'compare' => $compare,
        );
    }
    return $query_args;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


##USAGE:

Here we use the unused class argument to pass the price and the comparison operator.

1) DISPLAY PRODUCTS BELOW A SPECIFIC AMOUNT (YOUR CASE)

You will paste the following shortcode example with as class argument value below-999 (for products that have a price below 999):

[products limit="16" paginate="true" columns="4" class="below-999"]

The wordpress page text content editor:

enter image description here

You will get:

enter image description here

2) DISPLAY PRODUCTS ABOVE A SPECIFIC AMOUNT

You will paste the following shortcode example with as class argument value above-50 (for products that have a price above 50):

[products limit="16" paginate="true" columns="4" class="above-50"]

Available shortcode arguments and settings: Woocommerce shortcodes documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.5k users

...