【问题标题】:Set a max displayed available stock quantity on Woocommerce archives for variable products在 Woocommerce 档案中为可变产品设置最大显示的可用库存数量
【发布时间】:2021-01-14 12:02:14
【问题描述】:

我想设置 Woocommerce 商店页面上的最大库存商品数量。

我正在使用Display the stock availability for all product types in Woocommerce archive pages 答案代码,它做得很好,显示了 Woocommerce 商店中各种可用的库存。

但我想显示一个最大数量,比如 50,如果库存实际上超过 50。如果库存中有 721 件商品,我只想将数字显示给客户 50。

我尝试在现有代码中添加另一个 if 语句,但它只是在显示中添加了另一行,显示实际总库存以及我的最大数量 50,如果总数超过 50。

【问题讨论】:

    标签: php wordpress woocommerce stock variable-product


    【解决方案1】:

    以下内容将限制袜子数量显示为 50,当它超过 50,对于可变产品:

    add_action( 'woocommerce_after_shop_loop_item', 'wc_loop_get_product_stock_availability_text', 10 );
    function wc_loop_get_product_stock_availability_text() {
        global $wpdb, $product;
    
        $max_stock_qty = 50; // Maximum Number of Available Stock qty
    
        // For variable products
        if( $product->is_type('variable') ) {
    
            // Get the stock quantity sum of all product variations (children)
            $stock_quantity = $wpdb->get_var("
                SELECT SUM(pm.meta_value) FROM {$wpdb->prefix}posts as p
                JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
                WHERE p.post_type = 'product_variation'
                AND p.post_status = 'publish' AND p.post_parent = '".get_the_id()."'
                AND pm.meta_key = '_stock' AND pm.meta_value IS NOT NULL
            ");
    
            if ( $stock_quantity > 0 ) {
                // Here we limit the sock quantity display to 50 when it's up to 50
                $stock_quantity = $stock_quantity >= $max_stock_qty ? $max_stock_qty : $stock_quantity;
                
                echo '<p class="stock in-stock">'. sprintf( __("%s in stock", "woocommerce"), $stock_quantity ).'</p>';
            } else {
                if ( is_numeric($stock_quantity) )
                    echo '<p class="stock out-of-stock">' . __("Out of stock", "woocommerce") . '</p>';
                else
                    return;
            }
        }
        // Other products types
        else {
            echo wc_get_stock_html( $product );
        }
    }
    

    代码在您的活动子主题(或活动主题)的functions.php 文件中。它应该可以工作。

    相关:Display the stock availability for all product types in Woocommerce archive pages

    【讨论】:

    • 是的,效果很好!感谢您的快速帮助。
    • 因为它不会让我投票,所以我认为它不会让我检查答案。现在完成。再次感谢!
    猜你喜欢
    • 2019-09-20
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2019-06-22
    相关资源
    最近更新 更多