'How to hide products with price higher than 1 on WooCommerce shop and archives pages

I'm using this code to hide products on the Shop Page where the product price is higher than 1.

However, without the desired result. Where does it go wrong?

My code:

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


Solution 1:[1]

  • You're close, add type

'type' => 'numeric' // specify it for numeric values

type (string) - Custom field type. Possible values are 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'. Default value is 'CHAR'.


  • compare (string) - Operator to test. 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). Values 'REGEXP', 'NOT REGEXP' and 'RLIKE' were added in WordPress 3.7. Default value is '='.

Result:

This will hide all products where the price is higher than 1, on the product archive page (shop)

function react2wp_hide_products_higher_than_1( $q, $query ) {
    // Returns true when on the product archive page (shop).
    if ( is_shop() ) {
        // Get any existing meta query
        $meta_query = $q->get( 'meta_query' );

        // Define an additional meta query 
        $meta_query[] = array(
            'key'        => '_price',
            'value'      => 1,
            'type'       => 'numeric', // specify it for numeric values
            'compare'    => '<'
        );

        // Set the new merged meta query
        $q->set( 'meta_query', $meta_query );
    }
}
add_action( 'woocommerce_product_query', 'react2wp_hide_products_higher_than_1', 10, 2 );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1