【问题标题】:Redirect when buying products from a certain product category in Woocommerce在 Woocommerce 中从某个产品类别购买产品时重定向
【发布时间】:2019-01-27 05:50:15
【问题描述】:

我有这个代码:

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;
    }
}

下单购买某类商品时,如何替换重定向条件?

例如,如果用户购买了某个类别的产品,那么当他尝试下订单时,他会重定向到注册并在成功注册后返回。

【问题讨论】:

    标签: php wordpress woocommerce cart custom-taxonomy


    【解决方案1】:

    当结帐页面中的未登录用户拥有来自特定产品类别的商品时,以下代码将重定向到我的帐户页面。您必须在代码中定义您的特定产品类别:

    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 文件中。经过测试并且可以工作。

    【讨论】:

    • 如果我添加return 'domain.com/cart/'; 注册后返回购物车是正确的决定吗?
    • @Dmitry template_redirect 钩子不是过滤器,而是一个动作钩子......所以你不必返回任何东西......同样在重定向之后 exit();是必需的和强制性的
    • 如何自动返回购物车?
    【解决方案2】:

    我最近需要这样做,这个解决方案对我有用。此解决方案在收到订单后在订单详细信息中检查项目所在的产品类别。因此,重定向将在付款后进行。

    add_action( 'template_redirect', 'woocommerce_redirect_after_checkout' );
    function woocommerce_redirect_after_checkout() {
      global $wp;
     
      if ( is_checkout() && ! empty( $wp->query_vars['order-received'] ) ) {
      
      $order_id  = absint( $wp->query_vars['order-received'] ); 
      $order = wc_get_order( $order_id );  
      $prod_category = [CAT ID OR SLUG];
    
      foreach( $order->get_items() as $item ) {
    
        if( has_term( $prod_category, 'product_cat', $item['product_id'] ) ) {
            // change below to the URL that you want to send your customer to
             $redirect_url = 'https://www.example.com/custom-thank-you/';
    
             wp_redirect($redirect_url );
    
            exit;
          }
        }   
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-01
      • 2022-07-11
      • 2019-08-16
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多