
在 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() 函数,以防止脚本继续执行。
使用方法:
将上述代码复制到你主题的 functions.php 文件中,或者使用代码片段插件。修改 $categories 数组,将 category-1,category-2,category-3 替换为你需要进行特殊重定向的产品类别 slug。 你可以在 WooCommerce 产品类别页面找到每个类别的 slug。修改 if (in_array(‘category-1’, $categories)) 等条件判断语句中的 URL,将其替换为你希望用户重定向到的实际感谢页面 URL。根据需要修改默认重定向 URL。
注意事项:
确保你已经正确安装并激活了 WooCommerce 插件。请备份你的 functions.php 文件,以防出现意外错误。强烈建议使用子主题来修改 functions.php 文件,以避免在主题更新时丢失自定义代码。务必替换代码中的占位符 URL 和类别 slug。exit() 函数至关重要,它可以防止脚本在重定向后继续执行,避免潜在的问题。
总结:
通过使用 WooCommerce 钩子和 WordPress 条件函数,我们可以轻松地根据用户购买的产品类别,将其重定向到不同的感谢页面,从而提供更个性化的购物体验。 记得替换示例代码中的类别 slug 和 URL,以适应你的实际需求。 这种方法可以显著提升用户满意度,并为特定产品或促销活动提供定制化的后续流程。
以上就是WooCommerce:根据产品类别自定义结账后的重定向的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1292138.html
微信扫一扫
支付宝扫一扫