File: /www/wwwroot/www.cytocare.cn/wp-content/themes/blocksy-child/functions-backup传递订单id.php
<?php
if (! defined('WP_DEBUG')) {
die( 'Direct access forbidden.' );
}
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
});
// 添加A网站商品到购物车
function add_product_to_cart_from_query() {
// Check if we are on the checkout page, and not in the admin area
if (!is_admin() && is_page('checkout')) {
// Check if the required query parameters are set
if (isset($_GET['product_id']) && isset($_GET['quantity']) && isset($_GET['order_id'])) {
$product_id = intval($_GET['product_id']);
$quantity = intval($_GET['quantity']);
$external_order_id = intval($_GET['order_id']); // 获取外部订单ID
// Retrieve the cart object
$cart = WC()->cart;
// 清空现有购物车内容
$cart->empty_cart();
// Retrieve the product to validate if it exists and can be purchased
$product = wc_get_product($product_id);
if ($product && $quantity > 0) {
// Check if the product can be added to the cart, considering stock status, etc.
$cart = WC()->cart;
$exists = $cart->find_product_in_cart($cart->generate_cart_id($product_id));
if (!$exists) {
// Add the product to the cart
$cart->add_to_cart($product_id, $quantity);
} else {
// Increment the quantity if the product already exists in the cart
$cart_item_key = $cart->generate_cart_id($product_id);
if (isset($cart->cart_contents[$cart_item_key])) {
$cart->set_quantity($cart_item_key, $cart->cart_contents[$cart_item_key]['quantity'] + $quantity);
}
}
// Store the external order ID in session or transient for later use
WC()->session->set('external_order_id', $external_order_id);
// Optionally redirect to prevent duplicate additions on page refresh
wp_safe_redirect(esc_url(remove_query_arg(array('product_id', 'quantity', 'order_id'))));
exit;
}
}
}
}
add_action('wp', 'add_product_to_cart_from_query');