PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, May 15, 2022

[FIXED] How to hide products with price higher than 1 on WooCommerce shop and archives pages

 May 15, 2022     php, product, woocommerce, wordpress     No comments   

Issue

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

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


Answered By - 7uc1f3r
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing