首页 > 解决方案 > 从结帐到我的帐户并返回 Woocommerce 的自定义重定向

问题描述

WordPress 和 WooCommerce 上有一个网站。目前,在用户购买产品时,我已经具备了几个条件的功能:

  1. 如果用户没有注册,并且购买了订阅以外的任何产品,他会冷静地制定订单,系统会自动为他创建一个帐户。(完毕)

  2. 如果用户已经注册但忘记在他的登录名下输入,他也只需在结帐页面上的登录名下登录就可以悄悄地制定订单。(完毕)

  3. 如果用户未注册并想购买订阅,系统会将其重定向到注册页面,从那里到编辑帐户页面,然后他返回结帐页面。(完毕)

  4. 如果用户已注册但忘记使用他的登录名登录,并且他想购买订阅。用户重定向到注册页面。他输入登录名和密码。系统将他重定向回结帐页面。(一个任务)

我创建的前两个条件是标准的 WooCommerce 设置。对于第三个条件,我有可以看到的代码:

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 = 'subscriptions';

$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('/my-account/edit-account/');                
        exit();
}

if (is_user_logged_in() && !WC()->cart->is_empty() && is_account_page()) {
    wp_redirect( get_permalink( get_option('woocommerce_checkout_page_id') ) );
}

}

对于第四个条件,我添加了代码:

if (is_user_logged_in() &&! WC()->cart->is_empty() && is_account_page ()) {
    wp_redirect (get_permalink (get_option ('woocomm erce_checkout_page_id'))));
}

但它不能正常工作。由于此代码,第三个条件停止工作。

如何补救?谢谢!


更新:我把它保存在这里。这可以帮助其他用户。代码完全正常工作。

add_action( 'template_redirect', 'custom_redirections' );
function custom_redirections( $redirect ) {
// HERE set your product category (can be term IDs, slugs or names)
$category = 'subscriptions';

$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();
} elseif ( is_user_logged_in() && is_account_page() && $found  ) {
    wp_redirect( get_permalink( get_option('woocommerce_checkout_page_id') ) );
    exit();
}
}

标签: phpwordpressredirectwoocommercecheckout

解决方案


推荐阅读