首页 > 解决方案 > 感谢 WooCommerce 订单项目中特定产品 ID 的页面重定向

问题描述

我的一个产品需要一个特定的感谢页面。

这是我的代码。产品 ID 是1813,类别是gimnasio-mental。我真的不需要,也不想在这段代码中包含类别,所以如果它可以简化,那就更好了!

add_action( 'template_redirect', 'wc_custom_redirect_after_purchase' );
function wc_custom_redirect_after_purchase() {
    if ( ! is_wc_endpoint_url( 'order-received' ) ) return;

    // Define the product IDs in this array
    $product_ids = array( 1813 ); // or an empty array if not used
    // Define the product categories (can be IDs, slugs or names)
    $product_categories = array( 'gimnasio-mental' ); // or an empty array if not used
    $redirection = false;

    global $wp;
    $order_id =  intval( str_replace( 'checkout/order-received/', '', $wp->request ) ); // Order ID
    $order = wc_get_order( $order_id ); // Get an instance of the WC_Order Object

    // Iterating through order items and finding targeted products
    foreach( $order->get_items() as $item ){
        if( in_array( $item->get_product_id(), $product_ids ) || has_term( $product_categories, 'product_cat', $item->get_product_id() ) ) {
            $redirection = true;
            break;
        }
    }

    // Make the custom redirection when a targeted product has been found in the order
    if( $redirection ){
        wp_redirect( home_url( '/gracias-gimnasio-mental/' ) );
        exit;
    }
}

标签: phpwordpresswoocommerceproductorders

解决方案


你可以使用woocommerce_thankyou动作钩子来对付template_redirect

通过代码中添加的注释标签进行解释

function action_woocommerce_thankyou( $order_id ) {
    if( ! $order_id ) {
        return;
    }

    // Instannce of the WC_Order Object
    $order = wc_get_order( $order_id ); 

    // Is a WC_Order
    if ( is_a( $order, 'WC_Order' ) ) {
        // False
        $redirection = false;
        
        // Loop through order items
        foreach ( $order->get_items() as $item_key => $item ) {
            // Product ID(s)
            $product_ids = array( $item->get_product_id(), $item->get_variation_id() );
            
            // Product ID in array
            if ( in_array( 1813, $product_ids ) ) {
                $redirection = true;
            }
        }
    }

    // Make the custom redirection when a targeted product has been found in the order
    if ( $redirection ) {
        wp_safe_redirect( home_url( '/gracias-gimnasio-mental/' ) );
        exit;
    }
}
add_action( 'woocommerce_thankyou', 'action_woocommerce_thankyou', 10, 1 );

推荐阅读