如何隐藏价格高于1的产品

时间:2020-05-28 09:43:06

标签: php wordpress woocommerce

我正在使用此代码在商品价格高于1的商店页面上隐藏商品。

但是,没有期望的结果。哪里出问题了?

我的代码:

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

1 个答案:

答案 0 :(得分:1)

  • 您将关闭,添加type

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

    类型(字符串)-自定义字段类型。可能的值为'NUMERIC''BINARY''CHAR''DATE''DATETIME''DECIMAL''SIGNED''TIME''UNSIGNED'。默认值为'CHAR'


  • 比较(字符串)-要测试的运算符。可能的值为'=''!=''>''>=''<''<=''LIKE''NOT LIKE''IN''NOT IN''BETWEEN''NOT BETWEEN''EXISTS'(仅在WP> = 3.5中)和'NOT EXISTS'(也仅在WP中> = 3.5)。在WordPress 3.7中添加了值'REGEXP''NOT REGEXP''RLIKE'。默认值为'='

结果:

这将在产品归档页面(商店)中隐藏价格高于1的所有产品

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