When changing woocommerce title hook the first item doesn't change

Viewed 14242

I have a strange behaviour that I don't understand

I've changed the woocommerce_shop_loop_item_title hook to add a link to the title of the product. This is my code inside functions.php

// Add HREF TO TITLE
function abChangeProductsTitleHook(){
    remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
    add_action('woocommerce_shop_loop_item_title', 'abChangeProductsTitle', 10 );
}
add_action( 'woocommerce_shop_loop_item_title', 'abChangeProductsTitleHook' );
function abChangeProductsTitle() {
    echo '<h2 class="woocommerce-loop-product_title"><a href="'.get_the_permalink().'">' . get_the_title() . '</a></h2>';
}

It works perfectly on all the products except the first one.

I've also made a similar change to another hook to change the thumbnail image to a background image and also this one doesn't work on the first product. It's always the first product even if I change the order of the products.

Below you see a screenshot of the the first row of products on the page and that the first one is displayed differently

First product is different

It would be really helpful if anyone knows that problem or can point me in the right direction .

Thank you very much Alex

2 Answers

Although the accepted answer works, but why do we have to remove the title and then add it back in again? We could simply filter it in the first place.

add_filter('the_title', 'your_shop_custom_title', 20, 2);

function your_shop_custom_title($the_title, $id)
{

  if (is_shop() && get_post_type($id) == 'product') : // runs only on the shop page

    $the_title = '<a href="' . get_the_permalink() . '">' . $the_title . '</a>';

  endif;

  return $the_title;
}
Related