重定向缺货产品自定义页面
问题描述:
我有一个WooCommerce商店,我出售很多产品,每个只有1件。重定向缺货产品自定义页面
在销售了独特的数量产品后,我会自动显示“缺货”,但我想将此产品页面重定向到自定义页面。
我搜索了很多小时的Plugin => Nothing。
您有解决方案吗?
感谢。
答
使用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
}
}
代码放在您的活动子主题(或主题)的function.php文件或也以任何插件文件。
你刚才设置正确的页ID为重定向(而不是产品页面)。
更新:您可以使用经典的WordPress wp
行动挂钩(如果你得到一个错误或白页)。
在这里,我们需要再针对单个产品的网页,也得到$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
}
}
}
代码放在您的活动子主题(或主题)的function.php文件或也以任何插件文件。
该代码已经过测试和工作。
答
add_action('wp', 'wh_custom_redirect');
function wh_custom_redirect() {
//for product details page
if (is_product()) {
global $post;
$product = wc_get_product($post->ID);
if (!$product->is_in_stock()) {
wp_redirect('http://example.com'); //replace it with your URL
exit();
}
}
}
代码发送到您活动的子主题(或主题)的function.php文件中。或者也可以在任何插件php文件中使用。
代码已经过测试和工作。
希望这会有所帮助!
感谢您的回答。您的代码正确检测到“If is in Stock”,但重定向不起作用。滞留在空白页面... – LionelF
@LionelF我已经使用经典**''wp'' ** wordpress动作钩替代了我的代码。这次应该没问题。在第一个代码片段代码中,如果在产品页面上进行重定向,则可能会出现错误。 – LoicTheAztec
现在工作完美!谢谢 – LionelF