0

When you run get_post_meta( get_the_ID(), '_crosssell_ids',true); you get an array of all the products that the current product cross sells to.

How do I reverse that? To get all the products that cross sells to the current item?

Example:

Not this: Product 1 -> Cross-sell: Product 2, Product 3

But this: Product 3 <- Cross-sell: Product 1

0

You could do it with a meta query

$current_post_id = 'YOUR_POST_ID';

$args = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'meta_query' => array(
        array(
            'key' => '_crosssell_ids',
            'value' => $current_post_id,
            'compare' => 'LIKE'
        )
    )
);

$query = new WP_Query($args);

if($query->have_posts()){
    while($query->have_posts()): $query->the_post();
        $product = wc_get_product(get_the_ID());

        // Do what you want with the product.
    endwhile;
}

This query will return all products that have the $current_post_id as a cross sell id.

Hope this helps.

  • Your code works perfectly! I have a follow up question. If i'd like the $products to be looped out like the below structure, do you have any tips on how to achieve that? <div> <h2>Category 1 Name</h2> <p>Product in category 1</p> <p>Product in category 1</p> <p>Product in category 1</p> <h2>Category 2 Name</h2> <p>Product in category 2</p> <p>Product in category 2</p> <p>Product in category 2</p> </div> – Gustav Gesar Nov 9 '18 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.