将缺货产品重定向到自定义页面

Redirect Out of Stock Product to custom page

我有一家 WooCommerce 商店,我销售很多产品每件只有 1 件

销售唯一数量的产品后,我自动显示 "Out of stock",但我想将此产品页面重定向到自定义页面。

我搜索了很多小时来寻找插件 => 没有。

你有解决办法吗?

谢谢。

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 文件中。
代码已经过测试并且有效。

希望对您有所帮助!

使用挂钩在 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 文件或任何插件文件。

You will have just to set the correct page ID for the redirection (not a product page).


更新:您可以使用经典的 WordPress wp 操作挂钩 (如果您获得错误或白页).

这里我们还需要定位单个产品页面,还需要获取 $product 对象 的实例(使用 post 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 文件或任何插件文件。

代码已经过测试并且有效。