首页 > 解决方案 > 将购买特定产品的客户从单个产品页面重定向

问题描述

我尝试重定向购买了 ID 为“12514”产品的客户。

我的问题是:

如果用户已经购买过该产品一次,我在哪里可以设置产品 ID,以便仅在该单个页面上开始重定向(现在它在每个产品页面上)?

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;
    }
}

标签: phpwordpressredirectwoocommercehook-woocommerce

解决方案


只需在 if 语句中添加一个额外的条件

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;
    }
}

推荐阅读