【问题标题】:WooCommerce Custom Thankyou redirection based on Product ID基于产品 ID 的 WooCommerce 自定义Thankyou 重定向
【发布时间】:2023-03-29 21:47:01
【问题描述】:

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

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
  • 您的代码有什么问题?你有什么要求。就目前而言,我认为这个问题过于宽泛。

标签: php wordpress woocommerce url-redirection orders


【解决方案1】:

这是一个简单的页面重定向示例:

add_action( 'template_redirect', 'wc_custom_redirect_after_purchase');

function bbloomer_redirectcustom( $order_id ){
$order = new WC_Order( $order_id );

$url = 'http://yoursite.com/custom-url';

if ( $order->status != 'failed' ) {
    wp_redirect($url);
    exit;
  }
}  

【讨论】:

    【解决方案2】:

    在该功能下方,您必须设置目标产品 ID 或产品类别,以便在订单中的这些项目获得自定义重定向:

    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 上测试并有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多