简体   繁体   English

在 Woocommerce 元查询中检查库存的最佳方法是什么

[英]What is the best approach to checking stock in a Woocommerce meta query

I'm creating a one-way relationship between two products, with the 'linked-to' product outputting the product information of the 'linked-from' product.我正在两个产品之间创建一种单向关系,“链接到”产品输出“链接自”产品的产品信息。

I'm able to use a custom field to create the relationship, and use a meta query to generate the results based on this field, but I also need to check that the 'linked-from' product is still either In Stock (if not being stock managed), or has more than 0 as a stock quantity.我可以使用自定义字段创建关系,并使用元查询根据该字段生成结果,但我还需要检查“链接自”产品是否仍然有货(如果没有库存管理),或库存数量大于 0。

This is the approach I have taken so far, which returns no matching results (when indeed there are matches):这是我到目前为止采用的方法,它不返回任何匹配结果(当确实有匹配时):

$the_query = new WP_Query(array(
    'posts_per_page' => -1,
    'post_type'     => 'product',
    'meta_key'      => 'exact_new_version',
    'meta_value'    => $product->get_id(),
    'meta_query'     => array(
        'relation' => 'OR',
        array(
            'key' => '_stock_status',
            'value' => array('instock'),
            'compare' => 'IN',
        ),
        array(
            'key'     => '_stock_quantity',
            'value'   => 0,
            'compare' => '>'
        )
    )
));

The alternative is to check the stock of the returned match(es) in the query loop, but I imagine this to be far less efficient.另一种方法是检查查询循环中返回的匹配项的存量,但我认为这效率要低得多。

I've managed to achieve the desired result by passing in two sets of associative arrays into the meta query with an AND relationship, one of which (checking stock) containing a further two nested assoc.通过将两组关联数组传递到具有 AND 关系的元查询中,我设法获得了预期的结果,其中一组(检查库存)包含另外两个嵌套关联。 arrays with an OR relationship.具有 OR 关系的数组。

Essentially, the meta value has to match either an 'instock' item (if stock control isn't being used), or an item with '> 0' in stock, if it is:本质上,元值必须匹配“instock”项目(如果未使用库存控制)或库存“> 0”的项目,如果它是:

$the_query = new WP_Query(array(
'posts_per_page' => -1,
    'post_type'     => 'product',
    'meta_query' => 
     array(
    'relation' => 'AND',//*
     array(
    'key' => 'new_version', 
            'value' => $product->get_ID(),
            'compare' => 'LIKE',
        ),
        array(
        'relation' => 'OR', //**
        array(
           'key' => '_stock_status',
                'value' => array('instock'),
                'compare' => 'IN',
        ),
        array(
                'key'     => '_stock_quantity',
                'value'   => 0,
                'compare' => '>',
        ),

     ),
    ),
));     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM