在 WooCommerce 商店中,根据用户购买的产品类别将其重定向到不同的感谢页面,可以提供更个性化的购物体验。以下代码展示了如何实现这一功能。
add_action( 'template_redirect', 'order_received_redirection_to_custom_page' ); function order_received_redirection_to_custom_page() { // 仅在 "订单已接收" 页面执行 if( is_wc_endpoint_url('order-received') ) { global $wp; // 定义你的产品类别数组 $categories = array('category-1', 'category-2', 'category-3'); $order_id = absint($wp->query_vars['order-received']); $order = wc_get_order( $order_id ); // 获取订单对象 $category_found = false; // 遍历订单中的商品 foreach( $order->get_items() as $item ){ if( has_term( $categories, 'product_cat', $item->get_product_id() ) ) { $category_found = true; break; } } if( $category_found ) { // 根据类别重定向到不同的页面 if (in_array('category-1', $categories)) { $redirect_url = 'https://example.com/thank-you-category-1/'; } elseif (in_array('category-2', $categories)) { $redirect_url = 'https://example.com/thank-you-category-2/'; } else { $redirect_url = 'https://example.com/thank-you-category-3/'; } wp_redirect( $redirect_url ); exit(); // 务必加上 exit() } else { // 如果订单中没有指定类别的商品,则重定向到默认页面 $default_redirect_url = 'https://example.com/default-thank-you/'; wp_redirect( $default_redirect_url ); exit(); } } }
代码解释:
add_action( 'template_redirect', 'order_received_redirection_to_custom_page' );: 将自定义函数 order_received_redirection_to_custom_page 挂载到 template_redirect 钩子上。这个钩子在 WordPress 模板加载之前触发,允许我们在页面渲染之前进行重定向。
is_wc_endpoint_url('order-received'): 检查当前是否为 WooCommerce 的 "订单已接收" 页面。
$categories = array('category-1', 'category-2', 'category-3');: 定义一个包含需要进行特殊重定向的产品类别 slug 的数组。请务必根据你的实际情况修改此数组。
$order = wc_get_order( absint($wp->query_vars['order-received']) );: 获取订单对象。$wp->query_vars['order-received'] 包含订单 ID。wc_get_order() 函数根据订单 ID 获取订单对象。
foreach( $order->get_items() as $item ): 循环遍历订单中的每个商品。
has_term( $categories, 'product_cat', $item->get_product_id() ): 使用 has_term() 函数检查当前商品是否属于 $categories 数组中的任何一个类别。'product_cat' 指定了 taxonomy 为 product_cat (产品类别)。
wp_redirect( $redirect_url );: 使用 wp_redirect() 函数将用户重定向到指定的 URL。
exit();: 在 wp_redirect() 之后,务必调用 exit() 函数,以防止脚本继续执行。
使用方法:
注意事项:
总结:
通过使用 WooCommerce 钩子和 WordPress 条件函数,我们可以轻松地根据用户购买的产品类别,将其重定向到不同的感谢页面,从而提供更个性化的购物体验。 记得替换示例代码中的类别 slug 和 URL,以适应你的实际需求。 这种方法可以显著提升用户满意度,并为特定产品或促销活动提供定制化的后续流程。
以上就是WooCommerce:根据产品类别自定义结账后的重定向的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号