php - 感谢 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;
}
}
解决方案
你可以使用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 );
推荐阅读
- sql - 如何以直接、简单的方式获取 MS SQL Server 和数据库空间信息
- python - 同时运行多个使用用户输入和while循环的python脚本
- php - $request 根据我转储它的位置返回不同的值
- amazon-web-services - AWS:Lambda 权限策略可以使用通配符从目标组获取源吗?
- python - Python Jupyter Notebook 无法运行我的代码,不断重新连接
- ruby-on-rails - rails 6外键不能为空
- c# - IFormFile 作为嵌套的 ViewModel 属性
- laravel - 使用 Eloquent 从相关表外键中检索值
- php - 如何使表格上显示的数据随着选择框中选择的值而变化?
- javascript - 如果我的 API 位于不同的“路线”,我该如何访问它?