【问题标题】:WooCommerce custom checkout page redirection for specific product categories针对特定产品类别的 WooCommerce 自定义结帐页面重定向
【发布时间】:2020-10-18 12:37:23
【问题描述】:

如果您从产品类别“特殊”购买产品,您应该从 /checkout/ 重定向到 /newcheckout/。

当我运行此代码时,没有任何重定向/发生,所以我不确定故障出在哪里:

/*
 * Redirect payment gateway based on category.
 */
function ace_disable_payment_gateway_category( $gateways ) {
    // Categories that'll redorect the payment gateway 
    $category_slugs = array( 'special');
    $category_ids = get_terms( array( 'taxonomy' => 'product_cat', 'slug' => $category_slugs, 'fields' => 'ids' ) );
    $url = '/newcheckout/'; // New checkout URL

    // Check each cart item for given category
    foreach ( WC()->cart->get_cart() as $item ) {
        $product = $item['data'];
if (is_page('checkout') {
        if ( $product && array_intersect( $category_ids, $product->get_category_ids() ) ) {
            wp_safe_redirect( $url ) // Redirect to newcheckout
            break;
        }
    }
}
    return $gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'ace_disable_payment_gateway_category' );

【问题讨论】:

    标签: php wordpress redirect woocommerce checkout


    【解决方案1】:

    重定向的最佳钩子是template_redirect 动作钩子。请注意,过滤器挂钩是为重定向而制作的。所以你的代码应该是:

    // Custom checkout page for specific product categories.
    add_filter( 'template_redirect', 'product_category_checkout_redirection' );
    function product_category_checkout_redirection() {
        // Only on checkout page
        if ( is_checkout() && ! is_wc_endpoint_url() ) :
    
        // Categories that redirects
        $product_categories = array( 'special'); // Product categories (can be a term Id, slug or name)
        $new_checkout_url   = home_url('/newcheckout/'); // New checkout URL
    
        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( has_term( $product_categories, 'product_cat', $cart_item['product_id'] ) ) {
                wp_safe_redirect( $new_checkout_url ); // Redirects to "newcheckout"
                exit();
            }
        }
    
        endif;
    }
    

    代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    【讨论】:

      猜你喜欢
      • 2017-12-16
      • 2016-07-16
      • 1970-01-01
      • 2016-08-06
      • 2021-02-25
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多