skip to Main Content

I am using Yoast WordPress plugin and the breadcrumb function that it provides. It works great, but I want to modify the default structure and to add an additional class.

So instead of:

<a href="http://www.example.com" rel="v:url" property="v:title">Home</a>

I want to make it:

<a href="http://www.example.com" class="my-class" rel="v:url" property="v:title">Home</a>

3

Answers


  1. Try Below Code in your function.php file in which you can add custom class to breadcrumb.

    add_filter( 'wpseo_breadcrumb_single_link', 'ss_breadcrumb_single_link', 10, 2 );
    function ss_breadcrumb_single_link( $link_output, $link ) {
    $element = '';
    $element = esc_attr( apply_filters( 'wpseo_breadcrumb_single_link_wrapper', $element ) );
    $link_output =  $element;
    
    if ( isset( $link['url'] ) ) {
        $link_output .= '<a rel="nofollow" href="' . 
    
     esc_url( $link['url'] ) . '" rel="v:url" property="v:title" class="my-class">' . 
    
     esc_html( $link['text'] ) . '</a>';
     }
     return $link_output;
    }
    
    Login or Signup to reply.
  2. Your comment works.

    //add class to yoast breadcrumb link
    add_filter( 'wpseo_breadcrumb_single_link', 'change_breadcrumb_link_class'); 
    function change_breadcrumb_link_class($link) {  
        return str_replace('<a', '<a class="my-class"', $link); 
    }
    
    Login or Signup to reply.
  3. If you need to add a breadcrumb name specific CSS class to each link, you could use the fallowing:

    /**
         * Helper function which will generate a valid CSS class 
         * from a breadcrumb link text name.
         *
         * @param string $string 
         * 
         * @return void 
         */
        function cleanString($string)
        {
            $string = remove_accents($string); // WordPress internal function
            $string = strtolower($string); // convert to lower case
            $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
            $string = preg_replace('/[^A-Za-z0-9-]/', '', $string); // Removes special chars.
        
            return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
        }
        
        /**
         * Modifies SEO Yeast breadcrumbs links through wpseo_breadcrumb_single_link filter
         *
         * @see https://stackoverflow.com/questions/42178688/how-to-add-a-class-to-the-a-tag-in-yoast-seo-breadcrumbs
         *
         */
        add_filter('wpseo_breadcrumb_single_link', 'ss_breadcrumb_single_link', 10, 2);
        function ss_breadcrumb_single_link($link_output, $link)
        {
            $classText = cleanString($link['text']);
            return str_replace('<a', '<a class="breadcrumbs-' . $classText . '"', $link_output);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search