Ad

Display ALL Cross-sell Items In WooCommerce Cart

- 1 answer

I'm trying to always display all cross-sell items in my cart.

The function get_cross_sells() located in the file class-wc-cart.php looks like this:

/**
 * Gets cross sells based on the items in the cart.
 *
 * @return array cross_sells (item ids)
 */
public function get_cross_sells() {
    $cross_sells = array();
    $in_cart     = array();
    if ( ! $this->is_empty() ) {
        foreach ( $this->get_cart() as $cart_item_key => $values ) {
            if ( $values['quantity'] > 0 ) {
                $cross_sells = array_merge( $values['data']->get_cross_sell_ids(), $cross_sells );
                $in_cart[]   = $values['product_id'];
            }
        }
    }
    $cross_sells = array_diff( $cross_sells, $in_cart );
    return apply_filters( 'woocommerce_cart_crosssell_ids', wp_parse_id_list( $cross_sells ), $this );
}

The line $cross_sells = array_diff( $cross_sells, $in_cart ); is what removes all cross-sell items that are already in the cart.


This "kinda" does it, but this way I'll have to make changes to the theme whenever I add or remove cross-sell items.

add_filter( 'woocommerce_cart_crosssell_ids', 'my_custom_cross_sells' );
function my_custom_cross_sells( $cross_sell_ids ){ 
    $cross_sell_ids = [4782, 4777, 4776, 4783]; 
    return $cross_sell_ids;
}

How would I go about to override this function from my child-theme to always display all items?

Ad

Answer

The woocommerce_cart_crosssell_ids filter hook will allow you to completely rewrite the get_cross_sells() function.

So to display ALL cross-sell items in WooCommerce cart, you get:

function filter_woocommerce_cart_crosssell_ids( $cross_sells, $cart ) {
    // Initialize
    $cross_sells_ids_in_cart = array();
    
    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $values ) {
        if ( $values['quantity'] > 0 ) {
            // Merge one or more arrays
            $cross_sells_ids_in_cart = array_merge( $values['data']->get_cross_sell_ids(), $cross_sells_ids_in_cart );
        }
    }
    
    // Cleans up an array, comma- or space-separated list of IDs
    $cross_sells = wp_parse_id_list( $cross_sells_ids_in_cart );

    return $cross_sells;
}
add_filter( 'woocommerce_cart_crosssell_ids', 'filter_woocommerce_cart_crosssell_ids', 10, 2 );
Ad
source: stackoverflow.com
Ad