【问题标题】:Check if user has bought an item and redirect to a specific page检查用户是否购买了商品并重定向到特定页面
【发布时间】:2020-07-04 19:12:57
【问题描述】:

我有这个功能,但它没有按需要工作。改成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;
} 

【问题讨论】:

  • "...目标是检查用户是否购买了免费订阅产品(“11344”),当该用户尝试访问用户帐户中的特定页面时,它被重定向到另一个页面..." -- 您必须从该页面运行上述代码。您现在拥有的代码通常被应用。它是关于哪个页面的?它是 WooCommerce 中的默认页面吗?
  • 我有一个显示访问统计的页面,它是www.website.com/my-account/。我想隐藏那个页面,这样当购买了上述产品的用户尝试去那里时,就会被重定向到另一个页面 www.website.com/my-account/my-listings/

标签: php wordpress redirect woocommerce product


【解决方案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' );

【讨论】:

  • 非常感谢!按预期工作!请问,是否可以基于相同的产品 ID 隐藏特定选项卡(从用户菜单中)?是否可以使用 css 或 javascript?
  • 不推荐使用 CSS 或 JS。你可以使用的钩子是woocommerce_account_menu_items。看到一个类似的问题:WooCommerce - Remove downloads from menu in my account page(来自 LoicTheAztec 的回答),那么只需根据您的意愿调整代码即可。但是,请注意,您不应该在评论部分提出新问题。如有其他或新问题,请打开一个新主题
猜你喜欢
  • 2016-12-10
  • 2021-03-30
  • 2013-10-15
  • 2021-01-27
  • 2012-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
相关资源
最近更新 更多