【问题标题】:Woocommerce checking stock of several products in a DRY way?Woocommerce 以 DRY 方式检查几种产品的库存?
【发布时间】:2014-03-21 17:51:46
【问题描述】:

如何查看同一父类别的多个产品的多个产品的库存 以干燥的方式?我需要获取总库存和/或检查任何给定产品的库存是否不低于某个阈值。

到目前为止,我知道如何检索每个单独产品的库存,我需要 (1) 返回库存总量的值,以及 (2) 检查是否没有单独的值低于某个阈值。

这是我的代码:

<?php
$args = array(
    'post_type' => 'product',
    'product_cat' => 'name_of_my_category',
    'orderby' =>'date',
    'order' => 'DESC',
);

$name_of_my_query = new WP_Query( $args );
if ($name_of_my_query->have_posts()) : 
    while ($name_of_my_query->have_posts()) : 
        $name_of_my_query->the_post();
        $product = get_product( $name_of_my_query->post->ID );


echo $product->stock;
endwhile;
endif;
wp_reset_query();
?>

在这个阶段,我只能想到对每个产品重复此代码,将返回的每个值分配给不同的变量并总结它们……相当漫长的过程,我确定一定有更简单的方法吗?

感谢您的帮助!

【问题讨论】:

    标签: php wordpress stock


    【解决方案1】:

    您可以创建一个参数数组数组,并使用 foreach 语句循环遍历它们:

    $threshold = 100;
    
    $args_array = array(
        array(
            'post_type' => 'product',
            'product_cat' => 'name_of_my_category',
            'orderby' =>'date',
            'order' => 'DESC'
        ),
        array(
            'post_type' => 'product2',
            'product_cat' => 'name_of_my_category2',
            'orderby' =>'date',
            'order' => 'DESC'
        ),
        array(
            'post_type' => 'product3',
            'product_cat' => 'name_of_my_category3',
            'orderby' =>'date',
            'order' => 'DESC'
        )
    );
    
    
    foreach ($args_array as $args) {
        $name_of_my_query = new WP_Query( $args );
        if ($name_of_my_query->have_posts()) : 
            while ($name_of_my_query->have_posts()) : 
                $name_of_my_query->the_post();
                $product = get_product( $name_of_my_query->post->ID );
                echo $product->stock;
                if((int)$product->stock <= $threshold){
                    //do stuff here to alert yourself that stock is low
                    echo "Stock is low on".$product->name;
                }
            endwhile;
        endif;
    
        wp_reset_query();
    }
    

    【讨论】:

    • 谢谢拉斯!太棒了,只是一点点知识就可以区分新手和专家!感谢您能弥合这一差距!只是澄清一下,以确保:每次循环发现库存不足的项目时,该 echo 语句都会触发,对吗?如果至少一件商品库存不足,我需要触发回声怎么办?再次感谢!
    • 关于如何获得数组库存总数的任何提示?谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-11-19
    • 2019-01-27
    • 2019-07-31
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多