如果缺货,在特定的 WooCommerce 产品页面中输出自定义代码
Output custom code In a specific WooCommerce product page if out of 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"
元素内。
想法?
想通了!我的错误是没有在 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 } ?>
与其覆盖 WooCommerce 模板,不如将代码嵌入到 woocommerce_single_product_summary
操作挂钩中的函数中,这样:
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 文件。
此代码已经过测试并且有效。
我正在尝试检查用户是否在特定产品页面上,然后如果产品缺货。如果产品没有库存,我想显示一个可选的促销图片,将另一个产品添加到购物车。
使用当前代码时出现错误,页面在到达此代码段时停止呈现。
现在我的代码如下:
<?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"
元素内。
想法?
想通了!我的错误是没有在 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 } ?>
与其覆盖 WooCommerce 模板,不如将代码嵌入到 woocommerce_single_product_summary
操作挂钩中的函数中,这样:
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 文件。
此代码已经过测试并且有效。