Site icon Hip-Hop Website Design and Development

Add class to anchor links and other elements in a widget

I’m building a theme that follows the BEM methodology.

I’ve added the following to functions.php:

function nav_bem_anchor_element( $atts, $item, $args, $depth ) {
    $atts['class'] = 'header__nav-anchor';
    return $atts;
}
add_filter( 'nav_menu_link_attributes', 'nav_bem_anchor_element', 10, 4 );

This adds a class to each anchor link in my nav, like so:

<a href="#" class="header__nav-anchor">Nav Item</a>

I’d like to do the same for the widget area. Is this possible?

I’m also looking to add a class to other elements like <p> and <h2>. I understand you can wrap titles via an array ('before_title' and 'after_title'), but this doesn’t seem to work with the new Gutenberg widgets.