如何在 WooCommerce 商店页面上隐藏库存少于 2 的产品

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

我经营一家电子商务公司,我想隐藏库存少于 3 件的产品。

这就是我想出的:

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

您设置过类似的代码吗?此行有任何错误吗?

你很接近,添加 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 );