Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tdiphale/41f46d43e72078acb092d0d28b252d9d to your computer and use it in GitHub Desktop.
Save tdiphale/41f46d43e72078acb092d0d28b252d9d to your computer and use it in GitHub Desktop.
WordPress: add class to LI and A elements output by wp_nav_menu()
<?php
// Add class to A element of .primary-menu
function tps_primary_menu_anchor_class($item_output, $item, $depth, $args) {
$item_output = preg_replace('/<a /', '<a class="nav-link" ', $item_output, 1);
return $item_output;
}
add_filter('walker_nav_menu_start_el', 'tps_primary_menu_anchor_class', 10, 4);
// Add class to LI element of .primary-menu
function tps_primary_menu_li_class($objects, $args) {
foreach($objects as $key => $item) {
$objects[$key]->classes[] = 'nav-item';
}
return $objects;
}
add_filter('wp_nav_menu_objects', 'tps_primary_menu_li_class', 10, 2);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment