[英]Redirecting Woocommerce purchase to a unique page per product category
I used a code to redirect the buyer to a customised page.我使用代码将买家重定向到自定义页面。 But I would like to add a different redirect per product category as set in Woocommerce.
但我想为 Woocommerce 中设置的每个产品类别添加不同的重定向。
This is the code I'm using to redirect for all purchases.这是我用来重定向所有购买的代码。 Now I need to change it to a redirect per categegory.
现在我需要将其更改为每个类别的重定向。 For example if someone buys a shop product it goed to page A and when they purchase a course it goes to page B after purchase.
例如,如果有人购买商店产品,它会转到页面 A,而当他们购买课程时,它会在购买后转到页面 B。
<?php
/* Redirect user after check out */
add_action( 'template_redirect', 'jay_custom_redirect_after_purchase' );
function jay_custom_redirect_after_purchase() {
global $wp;
if ( is_checkout() && ! empty( $wp->query_vars['order-received'] ) ) {
wp_redirect( 'http://www.yoururl.com/your-page/' );
exit;
}
}
In my suggestion I changed the action you selected to allow get order id.在我的建议中,我更改了您选择的操作以允许获取订单 ID。 So with this informations I obtained the order items and its categories.
因此,通过这些信息,我获得了订单项目及其类别。
add_action( 'woocommerce_thankyou', 'jay_custom_redirect_after_purchase', 10, 1 );
function jay_custom_redirect_after_purchase($order_id) {
$order = wc_get_order( $order_id );
$items = $order->get_items();
$categories_to_A = array('Shop');
$categories_to_B = array('Course');
foreach ( $items as $item ) {
if ( has_term( $categories_to_A, 'product_cat', $item['product_id'] ) ) {
wp_redirect( 'http://www.yoururl.com/your-page-a/' );
exit;
}
if ( has_term( $categories_to_A, 'product_cat', $item['product_id'] ) ) {
wp_redirect( 'http://www.yoururl.com/your-page-b/' );
exit;
}
}
}
You can use the woocommerce_thankyou
hook.您可以使用
woocommerce_thankyou
挂钩。
add_action( 'woocommerce_thankyou', 'redirect_after_checkout' );
function redirect_after_checkout( $order_id ) {
if ( $order->has_status( 'failed' ) ) {
return;
}
// set the product category slugs to redirect to
$url_cat_A = 'https://yoursite.com/category-A';
$url_cat_B = 'https://yoursite.com/category-B';
$order = wc_get_order( $order_id );
foreach ( $order->get_items() as $item ) {
$product = $item->get_product();
// if the product belongs to category A redirects to the product category page A
if ( has_term( 'slug_cat_A', 'product_cat', $product->get_id() ) ) {
wp_safe_redirect( $url_cat_A );
exit;
}
// if the product belongs to category B redirects to the product category page B
if ( has_term( 'slug_cat_B', 'product_cat', $product->get_id() ) ) {
wp_safe_redirect( $url_cat_B );
exit;
}
}
}
If the order contains a product from a certain category, it redirects to the corresponding product category page.如果订单包含某个类别的产品,它会重定向到相应的产品类别页面。
The code must be added to the functions.php of your active theme.代码必须添加到您的活动主题的functions.php。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.