Reputation: 15733
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>
Upvotes: 3
Views: 3690
Reputation: 18840
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);
}
Upvotes: 1
Reputation: 810
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);
}
Upvotes: 2
Reputation: 3614
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;
}
Upvotes: 4