我使用代码将买家重定向到自定义页面。但我想为 Woocommerce 中设置的每个产品类别添加不同的重定向。
这是我用来重定向所有购买的代码。现在我需要将其更改为每个类别的重定向。例如,如果有人购买商店产品,它会转到 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;
}
}
答案 0 :(得分:0)
在我的建议中,我更改了您选择的操作以允许获取订单 ID。因此,根据这些信息,我获得了订单项目及其类别。
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;
}
}
}
答案 1 :(得分:0)
您可以使用 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;
}
}
}
如果订单包含某个类别的产品,则重定向到相应的产品类别页面。
代码必须添加到活动主题的functions.php中。