检查用户是否已购买商品并重定向到特定页面

时间:2020-07-04 09:10:13

标签: php wordpress redirect woocommerce product

我有此功能,但无法正常工作。将其更改为wc_customer_bought_product会更好吗?

目标是检查用户是否购买了免费的订阅产品“ 11344”,并在该用户尝试访问用户帐户中的特定页面时将其重定向到另一个页面。

我有一个页面,其中显示访问统计信息,页面为www.website.com/my-account/。我想隐藏该页面,以便当购买了上述产品的用户尝试去那里时,然后重定向到另一个页面,www.website.com/my-account/my-listings/

有人可以建议我需要在此代码中进行编辑吗?当前卡住了,因为此功能没有执行任何操作。

//You can make this code as function and call it where it is require
$current_user = wp_get_current_user();
if ( 0 == $current_user->ID ) return;

// GET USER ORDERS (COMPLETED + PROCESSING)
$customer_orders = get_posts( array(
    'numberposts' => -1,
    'meta_key'    => '_customer_user',
    'meta_value'  => $current_user->ID,
    'post_type'   => wc_get_order_types(),
    'post_status' => array_keys( wc_get_is_paid_statuses() ),
) );

// LOOP THROUGH ORDERS AND GET PRODUCT IDS
if ( ! $customer_orders ) return;
$product_ids = array();
foreach ( $customer_orders as $customer_order ) {
    $order = wc_get_order( $customer_order->ID );
    $items = $order->get_items();
    foreach ( $items as $item ) {
        $product_id = $item->get_product_id();
        $product_ids[] = $product_id;
    }
}
$product_ids = array_unique( $product_ids );

if (in_array("11344", $product_ids))
{
    wp_redirect("https://website.com/account2"); // Add redirect URL Here 
    exit;
} 

1 个答案:

答案 0 :(得分:1)

function action_template_redirect() {
    global $wp;
    
    // Retrieve the current user object.
    $current_user = wp_get_current_user();
    if ( $current_user->ID == 0 ) return;
    
    // DEBUG PURPOSES, UNCOMMENT IF NECESSARY
    //echo $wp->request;

    // On my-account page
    if( $wp->request == 'my-account' ) {
        // Set product ID
        $product_id = 11344;
        
        // If true
        if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id ) ) {
            // Redirect
            wp_safe_redirect('/my-account/my-listings/');
            exit;
        }   
    }
}
add_action( 'template_redirect', 'action_template_redirect' );