[英]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.