【问题标题】:Redirect Out of Stock Product to custom page将缺货产品重定向到自定义页面
【发布时间】:2017-02-27 14:38:05
【问题描述】:

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

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

我搜索插件好几个小时 => 什么都没有。

你有解决办法吗?

谢谢。

【问题讨论】:

    标签: php wordpress woocommerce product stock


    【解决方案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
        }
    }
    

    代码进入您的活动子主题(或主题)的 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 文件或任何插件文件中。

    代码已经过测试并且可以工作。

    【讨论】:

    • 感谢您的回答。您的代码正确检测到“如果有货”,但重定向不起作用。卡在空白页...
    • @LionelF 我已经使用经典的 'wp' wordpress 操作挂钩更新了我的代码。这一次应该可以正常工作。如果在产品页面上进行重定向,则在第一个 sn-p 代码上可能会出错。
    • 现在完美工作!谢谢
    【解决方案2】:
    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 文件中。
    代码已经过测试并且可以工作。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2022-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多