我有下面的 PHP 代码。它的作用是在结账用户被重定向到自定义页面后。在此自定义页面中,用户可以购买额外的商品(通过添加新商品来修改订单)。但问题是,当我尝试访问收到订单的页面时,我不断被重定向回自定义页面。
add_action('woocommerce_thankyou', 'upsell_redirect');
function upsell_redirect($order_id) {
if (!is_wc_endpoint_url('order-received')) {
return;
}
WC()->session->set('original_order_id', $order_id);
$upsell_page_url = home_url('/upsell-1');
wp_redirect($upsell_page_url);
exit;
}
add_action('template_redirect', 'process_upsell');
function process_upsell() {
if (is_page('upsell-1') && isset($_GET['woocommerce_checkout_place_order'])) {
$original_order_id = WC()->session->get('original_order_id');
if ($original_order_id) {
$original_order = wc_get_order($original_order_id);
$original_order->add_product(wc_get_product('875'));
$original_order->calculate_totals();
$original_order->save();
$order_received_url = $original_order->get_checkout_order_received_url();
wp_redirect($order_received_url);
exit;
}
}
}
您可以尝试以下操作,以避免收到订单时出现重定向问题:
add_action('woocommerce_checkout_order_created', 'set_wc_session_original_order_id');
function set_wc_session_original_order_id( $order ) {
WC()->session->set('original_order_id', $order->get_id());
}
add_action('template_redirect', 'custom_shop_order_process_redirects');
function custom_shop_order_process_redirects() {
if ( is_page('upsell-1') && isset($_GET['woocommerce_checkout_place_order'])) {
$order_id = WC()->session->get('original_order_id');
if ( $order_id > 0 ) {
$order = wc_get_order($order_id);
$order->add_product(wc_get_product('875'));
$order->calculate_totals(); // Already includes save() method
WC()->session->__unset('original_order_id'); // Remove session variable
wp_redirect( $order->get_checkout_order_received_url() );
exit;
}
} elseif ( is_wc_endpoint_url('order-received') && WC()->session->__isset('original_order_id') ) {
wp_redirect( home_url('/upsell-1') );
exit;
}
}
应该可以。