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

时间:2017-02-27 14:38:06

标签: php wordpress woocommerce product stock

我有一个WooCommerce商店,我销售的产品只有1件

在销售独特数量产品后,我会自动显示“缺货”,但我想将此产品页面重定向到自定义页面。

我搜索了许多小时的插件=>什么都没有。

你有解决方案吗?

感谢。

2 个答案:

答案 0 :(得分:4)

使用隐藏在 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文件中,或者放在任何插件文件中。

代码经过测试并有效。

答案 1 :(得分:0)

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

希望这有帮助!