我試圖在我的WooCommerce主題中實現自定義增值銷售功能。 當用戶添加產品時,我需要將其他產品(upsell)添加到購物車。這意味着我必須爲產品添加一個額外的參數,以便在產品從購物車中刪除時,我可以獲得關係產品/加售並刪除關聯的加售。WooCommerce在產品添加時將增加銷售產品添加到購物車
用戶可以通過複選框列表選擇這些加售產品。這裏是我的「內容單一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 ]);
時,可以看到額外的加售參數,但是當我從購物車頁面顯示購物車時,會從購物車中刪除加載參數。
有什麼想法?
感謝, E.
對於其他人,[強制塞爾斯(http://www.woothemes.com/products/force-sells/)手柄正是這個。 – helgatheviking