Skip to content
Advertisement

WooCommerce – Remove product title from breadcrumbs but keep all category hyperlinks

I’m using the following function to remove the product title from the breadcrumbs displayed on the product page:

add_filter( 'woocommerce_get_breadcrumb', 'ed_change_breadcrumb' );

function ed_change_breadcrumb( $breadcrumb ) {
    
  if(is_singular()){
        array_pop($breadcrumb);
    }
  
  return $breadcrumb;
}

It works in that it does remove the title, but it also stops the last category/sub-category from being a hyperlink. How can I fix that?

For example:

  • Original breadcrumb

    <a>Home</a> / <a>Category</a> / <a>Sub Category</a> / Product Title

  • Result of the above function

    <a>Home</a> / <a>Category</a> / Sub Category

I need the Sub Category to still be clickable after removing the product title from the breadcrumbs.

Thanks

Advertisement

Answer

Your code works but the last element in the breadcrumbs never contains a link through the code used in global/breadcrumb.php template file on line 34

  • This template can be overridden by copying it to yourtheme/woocommerce/global/breadcrumb.php.

So you can remove your filter hook and apply the following code in the template file so that it provides a link to the last element when is_product() is true

Note: is_product() – Returns true on a single product page. Wrapper for is_singular()

Replace

if ( ! empty( $breadcrumb ) ) {

    echo $wrap_before;

    foreach ( $breadcrumb as $key => $crumb ) {

        echo $before;

        if ( ! empty( $crumb[1] ) && sizeof( $breadcrumb ) !== $key + 1 ) {
            echo '<a href="' . esc_url( $crumb[1] ) . '">' . esc_html( $crumb[0] ) . '</a>';
        } else {
            echo esc_html( $crumb[0] );
        }

        echo $after;

        if ( sizeof( $breadcrumb ) !== $key + 1 ) {
            echo $delimiter;
        }
    }

    echo $wrap_after;

}

With

if ( ! empty( $breadcrumb ) ) {

    echo $wrap_before;

    foreach ( $breadcrumb as $key => $crumb ) {

        echo $before;

        if ( ! empty( $crumb[1] ) && sizeof( $breadcrumb ) !== $key + 1 ) {
            echo '<a href="' . esc_url( $crumb[1] ) . '">' . esc_html( $crumb[0] ) . '</a>';
        } else {
            if ( is_product() ) {       
                unset($crumb);
            } else {
                echo esc_html( $crumb[0] );
            }
        }

        echo $after;

        if ( sizeof( $breadcrumb ) !== $key + 1 ) {
            if ( is_product() && sizeof( $breadcrumb ) == $key + 2 ) {
                echo '';
            } else {
                echo $delimiter;
            }
        }
    }

    echo $wrap_after;

}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement