检查用户是否购买了某个物品,并将其重定向到特定页面。
检查用户是否购买了某个物品,并将其重定向到特定页面。
我有这个函数,但它的工作效果不尽如人意。改用wc_customer_bought_product
会更好吗?\n目标是检查用户是否购买了免费订阅产品\"11344
\",当该用户尝试访问用户账户中的特定页面时,将其重定向到另一个页面。\n我有一个显示访问统计数据的页面,地址是www.website.com/my-account/
。我想隐藏该页面,这样当购买了上述产品的用户尝试访问该页面时,会被重定向到另一个页面,地址是www.website.com/my-account/my-listings/
。\n有人能建议我需要在这段代码中编辑什么吗?目前卡住了,因为这段代码没有任何效果。\n
//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; }
原因:该问题的出现是因为需要判断用户是否购买了特定的物品,并根据判断结果重定向到相应的页面。
解决方法:通过使用WordPress和WooCommerce提供的一些函数和钩子,可以实现对用户购买记录的判断和页面重定向。
具体操作如下:
1. 使用template_redirect
钩子,在确定要加载的模板之前触发函数action_template_redirect
。
2. 在action_template_redirect
函数中,使用wp_get_current_user
函数获取当前用户对象。
3. 判断当前用户是否为游客,如果是,则返回。
4. 如果当前请求的页面为"my-account",则继续执行下面的逻辑。
5. 设置要判断的产品ID为11344。
6. 使用wc_customer_bought_product
函数判断当前用户是否购买了指定的产品。如果购买了,则进行重定向。
7. 使用wp_safe_redirect
函数将用户重定向到"/my-account/my-listings/"页面,并使用exit
函数终止脚本的执行。
此外,根据问题中的附加内容,如果想要隐藏特定选项卡(来自用户菜单),可以使用woocommerce_account_menu_items
钩子来实现。具体参考链接中提供了一个类似问题的解决方案,可以根据自己的需求进行代码的适应。
需要注意的是,在评论部分不应提出新的问题,如果有其他问题,请开启新的主题进行讨论。