Display on a page all products below a specific pr

2019-08-21 10:45发布

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?

2条回答
Ridiculous、
2楼-- · 2019-08-21 10:50

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

查看更多
戒情不戒烟
3楼-- · 2019-08-21 10:59
  • Create a new page template
  • Create a new page, assign new page template
  • On top of page template code (or using filters), use WP_query to query your products

See:

$query = new \WP_Query(
    [
      'posts_per_page' => -1,
      'post_type' => 'product',
      'meta_key' => '_price',
      'meta_value' => 999,
      'meta_compare' => '<',
      'meta_type' => 'NUMERIC'
    ]);
  • You can then use a while loop, or foreach on $query->posts to display your post
查看更多
登录 后发表回答