[英]How to add related products based on current products in woocommerce cart page?
目前,我正在嘗試根據添加到woocommerce購物車中的產品輸出相關產品。
這類似於我們在單個產品頁面上顯示它的方式,但是只針對一種產品,並且您知道我們可以在購物車中添加許多產品。 因此,如何解決我的問題?
首先,我要獲取購物車中的商品並檢索其相關產品(並合並和隨機播放)。 然后,將其作為woocommerce_related_products_args
過濾器中的post__in
查詢參數提供。
這是一個代碼示例:
function wp_234123ds_related_products_args($args)
{
global $woocommerce;
// Fetching cart contents
$items = $woocommerce->cart->get_cart();
// Checking if there is something in a cart
if (count($items) > 0) {
$related = array();
// Traversing through collection
foreach ($items as $item) {
// Fetching product
$product = wc_get_product($item['product_id']);
// Fetching and merging related product IDS
$related = array_merge($related, $product->get_related());
}
// Lets check if they have any related products
if (count($related) > 0) {
shuffle($related);
// Finally we overwrite the "post__in" argument
$args['post__in'] = $related;
}
}
return $args;
}
add_filter('woocommerce_related_products_args', 'wp_234123ds_related_products_args');
明智的是,使用瞬態來緩存相關產品計算的結果(為簡便起見,此處未顯示)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.