我有这个代码:
add_action('template_redirect', 'woo_custom_redirect');
function woo_custom_redirect( $redirect ) {
if (
! is_user_logged_in()
&& (is_checkout())
) {
wp_redirect( home_url( '/my-account/edit-account/' ) );
return $redirect;
}
}
如何在下单购买某个类别的产品时替换重定向条件?
例如,如果用户购买了某个类别的产品,那么当他尝试下订单时,他会重定向到注册并在注册成功后返回。
最佳答案
当非登录用户拥有特定产品类别的商品时,以下代码会将未登录用户重定向到我的帐户页面。您必须在代码中定义您的特定产品类别:
add_action('template_redirect', 'woo_custom_redirect');
function woo_custom_redirect( $redirect ) {
// HERE set your product category (can be term IDs, slugs or names)
$category = 'posters';
$found = false;
// CHECK CART ITEMS: search for items from our product category
foreach ( WC()->cart->get_cart() as $cart_item ){
if( has_term( $category, 'product_cat', $cart_item['product_id'] ) ) {
$found = true;
break;
}
}
if ( ! is_user_logged_in() && is_checkout() && $found ) {
wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );
exit();
}
}
代码进入事件子主题(或事件主题)的 function.php 文件。经过测试并有效。
关于php - 在 Woocommerce 中购买某个产品类别的产品时重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51941923/