Lio*_*elF 2 php wordpress product stock woocommerce
我有一个 WooCommerce 商店,我销售许多产品,每个产品只有 1 件。
销售唯一数量的产品后,我自动显示“缺货”,但我想将此产品页面重定向到自定义页面。
我搜索了很多小时的插件 => 没有。
你有解决办法吗?
谢谢。
使用钩在woocommerce_before_single_product动作钩子中的自定义函数,将允许您使用简单的条件 WC_product 方法重定向到您的自定义页面,所有产品(页面)当产品缺货时is_in_stock(),使用此非常紧凑且有效的代码:
add_action('woocommerce_before_single_product', 'product_out_of_stock_redirect');
function product_out_of_stock_redirect(){
global $product;
// Set HERE the ID of your custom page <== <== <== <== <== <== <== <== <==
$custom_page_id = 8; // But not a product page (see below)
if (!$product->is_in_stock()){
wp_redirect(get_permalink($custom_page_id));
exit(); // Always after wp_redirect() to avoid an error
}
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中。
您只需为重定向(而不是产品页面)设置正确的页面 ID 。
更新:您可以使用经典的 WordPresswp操作挂钩(如果您收到错误或白页)。
在这里,我们还需要定位单个产品页面并获取$product对象的实例(带有帖子 ID)。
所以代码将是:
add_action('wp', 'product_out_of_stock_redirect');
function product_out_of_stock_redirect(){
global $post;
// Set HERE the ID of your custom page <== <== <== <== <== <== <== <== <==
$custom_page_id = 8;
if(is_product()){ // Targeting single product pages only
$product = wc_get_product($post->ID);// Getting an instance of product object
if (!$product->is_in_stock()){
wp_redirect(get_permalink($custom_page_id));
exit(); // Always after wp_redirect() to avoid an error
}
}
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中。
该代码经过测试并有效。
| 归档时间: |
|
| 查看次数: |
1600 次 |
| 最近记录: |