Redirect Out of Stock Product to custom page
Using a custom function hooked in woocommerce_before_single_product
action hook, will allow you to redirect to your custom page, all products (pages) when product is out of stock using a simple conditional WC_product method is_in_stock()
, with this very compact and effective code:
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 }}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
You will have just to set the correct page ID for the redirection (not a product page).
Update: You can use the classic WordPress wp
action hook (if you get an error or a white page).
Here we need additionally to target the single product pages and also to get an instance of the $product
object (with the post ID).
So the code will be:
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 } }}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
The code is tested and works.
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(); } }}
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
Code is tested and works.
Hope this helps!