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

Monday, May 9, 2022

[FIXED] How to hide products with stock less than 2 on WooCommerce shop page

 May 09, 2022     php, product, stock, woocommerce, wordpress     No comments   

Issue

I own an e-Commerce business and i want to hide the products that have a stock of less than 3.

This is what i came up to:

add_action( 'woocommerce_product_query', 'react2wp_hide_products_with_stock_higher_than_two' );
function react2wp_hide_products_with_stock_higher_than_two( $q ){
    $meta_query = $q->get( 'meta_query' );
    $meta_query[] = array(
        'key'       => '_stock',
        'value'     => 2,
        'compare'   => '>'
    );
    $q->set( 'meta_query', $meta_query );
}

Have you ever set a similar code? Any errors in this line?


Solution

You're close, add type

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

function react2wp_hide_products_with_stock_higher_than_two( $q, $query ) {
    // Get any existing meta query
    $meta_query = $q->get( 'meta_query' );

    // Define an additional meta query 
    $meta_query[] = array(
        'key'       => '_stock',
        'value'     => 2,
        '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_with_stock_higher_than_two', 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