Amir
Amir

Reputation: 87

Redirect customers who purchased a specific product away from the single product page

I try to redirect customers, who bought the product with the ID "12514".

My question is:

Where can I set the product ID, so that only on that single page starts a redirection (now it is on every single product page), if the user already bought that product once?

add_action( 'template_redirect', 'single_product_redirect_logged_in_purchased' );

function single_product_redirect_logged_in_purchased() { 
    if ( ! is_product() && ! is_user_logged_in() ) return;  
    $current_user = wp_get_current_user();
    $product_id = get_queried_object_id();
    if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id ) ) {
        wp_safe_redirect('/custom-url');
        exit;
    }
}

Upvotes: 2

Views: 229

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29624

Just add a extra condition in the if statement

add_action( 'template_redirect', 'single_product_redirect_logged_in_purchased' );

function single_product_redirect_logged_in_purchased() { 
    if ( ! is_product() && ! is_user_logged_in() ) return;  
    $current_user = wp_get_current_user();
    $product_id = get_queried_object_id();
    if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id ) && $product_id == 12514 ) {
        wp_safe_redirect('/custom-url');
        exit;
    }
}

Upvotes: 2

Related Questions