Home > OS >  Woocommerce if product has upsells show badge in product listing
Woocommerce if product has upsells show badge in product listing

Time:11-24

I'm trying to make a dynamic product badge show in the product listings on a Woocommerce site. The product badge should only show if the product has upsells assigned to it.

I just did this on the single product page with good results using this code in the content-single-product.php file:

<?php if ( isset( $product ) && is_product() ) {
    $upsells = version_compare( WC_VERSION, '3.0', '<' ) ? $product->get_upsells() : $product->get_upsell_ids();
    if ( count( $upsells ) > 0 ) { ?>
        <span class="more_variants">Finns i fler varianter</span>
<?php } } ?>

However, since the product data for upsells isn't collected for single products in the listings I tried another approach by implementing this code to functions.php:

add_action( 'woocommerce_before_shop_loop_item', 'related_upsell_products', 15 );

function related_upsell_products() {
    global $product;

    if ( isset( $product ) && is_product() ) {
        $upsells = version_compare( WC_VERSION, '3.0', '<' ) ? $product->get_upsells() : $product->get_upsell_ids();

        if ( count( $upsells ) > 0 ) {
            echo '<span >Finns i fler varianter</span>';
        }
    }
}

The code in functions.php doesn't give me an error nor does it give me the result I want neither. It returns nothing. My honest thought was that global $product; would give me the extra product data needed to get information if the product in particular has upsell products assigned to it or not.

Any thoughts is very welcome! I've searched the forums and do not get much results about working with upsells in this way with Woocommerce at all. Probably because it's not very common to work with upsells as variants instead of variable products..

CodePudding user response:

I'm going to assume that you're on the shop page, when you say "products in the listings". If so, then you would need to:

  • Change your conditional check to is_shop().
  • Also call your global $product after you've checked for the shop page.

So your entire code would be something like this:

add_action('woocommerce_before_shop_loop_item', 'related_upsell_products', 15);

function related_upsell_products()
{
    if (is_shop()) {
        global $product;

        $upsells = version_compare(WC_VERSION, '3.0', '<') ? $product->get_upsells() : $product->get_upsell_ids();

        if (count($upsells) > 0) {
            echo '<span >Finns i fler varianter</span>';
        }
    }
}

And here's the result:

enter image description here

  • Related