Automatically redirect out of stock products that are also hidden to their category page.
(not tested yet)
add_filter('woocommerce_before_single_product_rl_hook', 'rl_hide_product', 1);
function rl_hide_product()
{
global $product;
if (!isset($product)){
return;
}
/* If product is hidden and out of stock it will likely not come back. Do a 301 to category */
if ($product->get_catalog_visibility() == "hidden"
&& !$product->is_in_stock())
{
wp_redirect( rl_get_category_link_from_product($product->get_id()), 301 );
}
/* If product is hidden and in stock, this is mots likely an error. Do a 302 to category for now and warn admin */
if ($product->get_catalog_visibility() == "hidden"
&& $product->is_in_stock())
{
wp_redirect( rl_get_category_link_from_product($product->get_id()), 302 );
wp_mail(get_option('admin_email'), "Hidden inStock product Found", "Product : " . $product->get_sku() . " is hidden, but in stock");
}
/* Out of stock, but visible. Can be error or temporary out of stock. Warn admin just in case */
elseif ($product->get_catalog_visibility() !== "hidden"
&& !$product->is_in_stock()){
wp_mail(get_option('admin_email'), "Out Of Stock product Accessed", "Product : " . $product->get_sku() . " - " . $product->get_id() . " is out of stock AND visible");
}
}
function rl_get_category_link_from_product($product_id)
{
$terms = get_the_terms( $product_id, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
return get_term_link((int)$product_cat_id);
}
}Code language: PHP (php)