'WooCommerce Product attribute hook before headers being sent by Wordpress

I have WooCommerce products with a custom attribute called _redirect, the attribute value could be any internal or external URL.

In some particular conditions, I would like to redirect users to the URL that belongs to the _redirect attribute of the given product.

My issue is :

Using a hook-like "woocommerce_before_single_product", I'm able to get the value of the _redirect attribute (the url I want to redirect the user to), but at this stage unfortunatly is to late to be able to use wp_redirect() (because headers were already sent by Wordpress).

If I try an earliest hook like "template_redirect" unfortunatly it's too early to get the product _redirect attribute.

I've tried different hooks but I was not abble to find the one that I need (if it exists). Have you guys any idea that can help with this?



Solution 1:[1]

add_action('wp', 'custom_redirect_product_pages', 99);

function custom_redirect_product_pages() {

    if (is_product()) {
        global $product;
        $product_obj = get_page_by_path($product, OBJECT, 'product');
        if (6798816 == $product_obj->ID) { // Change the attribute check here.
            wp_safe_redirect(home_url()); // Change the URL here
            exit;
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mujuonly