我正在尝试在我的 WooCommerce 主题中实现自定义加售功能。当用户添加产品时,我需要在其购物车中添加额外的产品(追加销售)。这意味着我必须向产品添加一个额外的参数,如果产品从购物车中删除,我可以获取关系产品/追加销售并删除相关的追加销售。
用户可以通过复选框列表选择这些追加销售产品。这是我的“content-single-product.php”WooCommerce 模板的概述:
<form action="<?php echo esc_url( $product->add_to_cart_url() ); ?>" class="cart" method="post" enctype="multipart/form-data">
<?php
// Get Upsells Product ID:
$upsells = $product->get_upsells();
if ( sizeof( $upsells ) == 0 ) return;
$meta_query = $woocommerce->query->get_meta_query();
// Get Upsells:
$args = array(
'post_type' => 'product',
'ignore_sticky_posts' => 1,
'no_found_rows' => 1,
'posts_per_page' => $posts_per_page,
'orderby' => $orderby,
'post__in' => $upsells,
'post__not_in' => array( $product->id )
);
$query = new WP_Query( $args );
if ( $query->have_posts() ): ?>
<ul>
<?php while ( $query->have_posts() ): $query->the_post(); ?>
<label for="upsell_<?php the_ID(); ?>"><input type="checkbox" name="upsells[]" id="upsell_<?php the_ID(); ?>" value="<?php the_ID(); ?>" /> <?php the_title(); ?></label>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
<button type="submit">Add to cart</button>
</form>
上面的代码已经简化..
然后,这是我添加到 functions.php 中的代码,它允许我将追加销售添加到购物车并为相关产品添加额外的行:
/**
* Add upsells as extra data for added product
*/
function add_upsells_to_cart( $cart_item_key ) {
global $woocommerce;
if ( empty( $_REQUEST['upsells'] ) || ! is_array( $_REQUEST['upsells'] ) )
return;
// Prevent loop
$upsells = $_REQUEST['upsells'];
unset( $_REQUEST['upsells'] );
// Add upsell_parent row (if not already existing) for the associated product
if ( ! $cart_item_data['upsells'] || ! is_array( $cart_item_data['upsells'] ) )
$cart_item_data['upsells'] = array();
// Append each upsells to product in cart
foreach( $upsells as $upsell_id ) {
$upsell_id = absint( $upsell_id );
// Add extra parameter to the product which contain the upsells
$woocommerce->cart->cart_contents[ $cart_item_key ]['upsells'] = $upsell_id;
// Add upsell to cart
$woocommerce->cart->add_to_cart( $upsell_id );
}
}
add_action( 'woocommerce_add_to_cart', 'add_upsells_to_cart' );
追加销售按预期添加到购物车,但额外的行似乎被 WC 中的某些东西删除了。
当我print_r( $woocommerce->cart->cart_contents[ $cart_item_key ] );
在前一个函数的末尾执行 a 时,额外的 upsells 参数是可见的,但是当我从购物车页面显示购物车时, upsells 参数会从购物车中删除。
任何想法?
谢谢,E。