基于产品 ID 的 WooCommerce 自定义谢谢重定向 [英] WooCommerce Custom Thankyou redirection based on Product ID

查看:81
本文介绍了基于产品 ID 的 WooCommerce 自定义谢谢重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据 WooCommerce 客户购买的产品将他们重定向到特定的感谢页面?我有一个产品需要填写表格以获取更多信息,我想将该表格放在感谢页面上.到目前为止,我拥有的代码如下,但这只是用于所有产品的通用感谢页面.

How can I redirect WooCommerce customers to a specific thank you page based on the products they purchased? I have one product that requires a form to be filled out for further information, and I would like to place that form on a thank you page. The code I have so far is below, but that's just for a generic thank you page for all products.

add_action( 'template_redirect', 'wc_custom_redirect_after_purchase' ); 

function wc_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 或产品类别,以便在这些项目在订单中时获得自定义重定向:

Below in that function you will have to set your targeted product IDs or product categories, to get a custom redirection for this items when they are in the order:

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( 37, 25, 50 ); // or an empty array if not used
    // Define the product categories (can be IDs, slugs or names)
    $product_categories = array( 'clothing' ); // 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( '/your-page/' ) );
        exit;
    }
}

代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中.

已在 WooCommerce 3 上测试并有效.

Tested on WooCommerce 3 and works.

这篇关于基于产品 ID 的 WooCommerce 自定义谢谢重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆