Search code examples
phptemplateswoocommerceproducthook-woocommerce

How to target WooCommerce product loops inside a function


loop/price.php

I tried this and works, but not sure is it good way or not

<?php if ( $price_html = $product->get_price_html() ) : ?>
    <?php add_filter( 'woocommerce_format_sale_price', 'test_loop_price', 10, 3 );
    ?>
    <span class="price"><?php echo $price_html; ?></span>
<?php endif; ?>

Solution

  • Yes, it's a bad idea as this is not the correct way to do it… Apparently, you are using a custom function named test_loop_price() and you didn't provide the code of that function in your question.

    First remove your custom code from loop/price.php template file.

    Then, you need to target WooCommerce product loop, inside that function like:

    
    add_filter( 'woocommerce_format_sale_price', 'test_loop_price', 10, 3 );
    function test_loop_price( $price, $regular_price, $sale_price ) {
        global $woocommerce_loop, $product;
    
        if ( ( is_product() && isset($woocommerce_loop['name']) && empty($woocommerce_loop['name']) ) ) {
            return $price;
        }
    
        ## Here below comes your existing code ##
    
        
        return $price;
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.