首页 文章

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

提问于
浏览
1

我有一个WooCommerce商店,我卖了很多产品 with only 1 pieces for each .

销售独特数量产品后,我会自动显示 "Out of stock" 但我想将此产品页面重定向到自定义页面 .

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

你有解决方案吗?

谢谢 .

2 回答

  • 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文件中 .
    Code is tested and works.

    希望这可以帮助!

  • 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 .


    Update: 您可以使用经典的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文件中,或者放在任何插件文件中 .

    代码经过测试和运行 .

相关问题