Search code examples
phpwordpresswoocommerceproduct

Display "Sold Out" text on External products with empty price in WooCommerce


Some Amazon imported products dont have price or are sold out but not removed from listings, and its breaking aligments.

Im trying to customize woocommerce/templates/loop/price.phptemplate file.

From this

<?php if ( $price_html = $product->get_price_html() ) : ?>
    <span class="price"><?php echo $price_html; ?></span>
<?php endif; ?>

To something like this

<?php if ( $price_html = $product->get_price_html() ) : 
    if (empty($price)) 
    { 
        echo '<a href="link">Sold Out</a>';} 
    else 
    { ?>
        <span class="price"><?php echo $price_html; ?></span>
    <?php }; ?>
<?php endif; ?>

But its not working properly as now all products are sold out.

What am I doing wrong?


Solution

  • You can try the following code instead of overriding price template. The code will make sure that the product is external and the price is zero or empty.

    function op_change_price_html( $price_html, $product ) {
       if ( 'external' === $product->get_type() && empty( $product->get_price() ) ) {
           return 'Sold Out';
       }
       return $price_html;
    }
    add_filter( 'woocommerce_empty_price_html', 'op_change_price_html', 10, 2 );
    add_filter( 'woocommerce_get_price_html', 'op_change_price_html', 10, 2 );