输出自定义代码如果缺货,请在特定的WooCommerce产品页面中输出

时间:2017-07-08 17:29:50

标签: php wordpress woocommerce product stock

我尝试检查用户是否在特定产品页面上,然后如果产品缺货。如果产品没有库存,我想显示一个可选的促销图片,将另一个产品添加到购物车。

使用当前代码,我收到错误,页面在到达此代码段时停止呈现。

现在我的代码如下:

<?php if (! $product->is_in_stock() && is_single('12005') ) { ?> 

        <div id="oos-promo">
            <a href="https://example.com/?add-to-cart=11820&quantity=1">
                <img src="https://example.com/wp-content/uploads/2017/07/product.jpg" alt="Promo" class="img-responsive">
            </a>
        </div>

    <?php } ?>

我将此代码放在嵌套在此模板文件的content-single-product.php元素内的"entry-summary"文件中。

思想?

2 个答案:

答案 0 :(得分:1)

想出来!我的错误是在if语句之前没有引入全局$ product变量,请参阅下面的最终代码:

<?php global $product; if (! $product->is_in_stock() && is_single('12005') ) { ?> 

    <div id="oos-promo">
        <a href="https://example.com/?add-to-cart=11820&quantity=1">
            <img src="https://example.com/wp-content/uploads/2017/07/product.jpg" alt="Promo" class="img-responsive">
        </a>
    </div>

<?php } ?>

答案 1 :(得分:1)

您应该将代码嵌入到 woocommerce_single_product_summary 操作挂钩中的函数中,而不是覆盖WooCommerce模板,这样:

add_action( 'woocommerce_single_product_summary', 'out_of_stock_custom_code', 3 );
function out_of_stock_custom_code() {
    // Including the WC_Product object
    global $product;

    if ( ! $product->is_in_stock() && $product->get_id() == 12005 ) {
        ?>
        <div id="oos-promo">
            <a href="?add-to-cart=11820&quantity=1">
                <img src="https://example.com/wp-content/uploads/2017/07/product.jpg" alt="Promo" class="img-responsive">
            </a>
        </div>
        <?php
    }
}

代码可以在您的活动子主题(或主题)的任何php文件中,也可以在任何插件的php文件中。

此代码经过测试并有效。