简体   繁体   中英

How to add related products based on current products in woocommerce cart page?

Currently I'm trying to output related products based on the products which were added to woocommerce cart.

It's similar to the way that we display it in the single product page but that is just for one product, and you know that we can add many products to the cart. Therefore, what will be the solution to my question?

First I'd fetch the cart items and retrieve their related products (and merge and shuffle them). Then I'd feed it as a post__in query argument in a woocommerce_related_products_args filter.

Here is a code sample:

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');

It would be wise to cache the result of the related products calculation using transients (not shown here for brevity).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM