簡體   English   中英

將 Woocommerce 購買重定向到每個產品類別的唯一頁面

[英]Redirecting Woocommerce purchase to a unique page per product category

我使用代碼將買家重定向到自定義頁面。 但我想為 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;
    }
}

在我的建議中,我更改了您選擇的操作以允許獲取訂單 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;
    }

    
}

}

您可以使用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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM