2017-02-27 40 views
1

我有一個WooCommerce商店,我出售很多產品,每個只有1件。重定向缺貨產品自定義頁面

在銷售了獨特的數量產品後,我會自動顯示「缺貨」,但我想將此產品頁面重定向到自定義頁面。

我搜索了很多小時的Plugin => Nothing。

您有解決方案嗎?

感謝。

回答

3

使用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文件或也以任何插件文件。

該代碼已經過測試和工作。

+0

感謝您的回答。您的代碼正確檢測到「If is in Stock」,但重定向不起作用。滯留在空白頁面... – LionelF

+0

@LionelF我已經使用經典**''wp'' ** wordpress動作鉤替代了我的代碼。這次應該沒問題。在第一個代碼片段代碼中,如果在產品頁面上進行重定向,則可能會出現錯誤。 – LoicTheAztec

+2

現在工作完美!謝謝 – LionelF

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文件中使用。
代碼已經過測試和工作。

希望這會有所幫助!

相關問題