当前位置: 首页 > 知识库问答 >
问题:

如何在woocommerce推车页面中添加基于当前产品的相关产品?

卫皓
2023-03-14

共有1个答案

狄溪叠
2023-03-14

首先,我将获取购物车项目并检索它们的相关产品(并合并和洗牌它们)。然后在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');

明智的做法是使用瞬变缓存相关乘积计算的结果(为简洁起见,此处未显示)。

 类似资料: