Add active class to current selected anchor in Wordpress - php

How to add active class to my anchor in Wordpress? Current code is below:
$args = array(
'theme_location' => 'primary',
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'menu_class' => 'nav navbar-nav navbar-right'
);
wp_nav_menu( $args );
I get this output for each menu item:
<li id="menu-item-42" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-42">
Services
</li>
But I want the 'a' tag to have an 'active' class, like I have shown below:
<li id="menu-item-42" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-42">
<a class="active" href="http://localhost:8888/axial/services/">Services</a>
</li>

Yes it's possible, try code below:
function add_class_to_href( $classes, $item ) {
if ( in_array('current_page_item', $item->classes) ) {
$classes['class'] = 'active';
}
return $classes;
}
add_filter( 'nav_menu_link_attributes', 'add_class_to_href', 10, 2 );

Just paste this code into functions.php file:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class ($classes, $item) {
if (in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}

You can do this with CSS.
you can use current-menu-item class which is added by default.
/*you have to add the active menu item styles like this*/
a{
padding:5px;
font-family:arial;
color:#333;
text-decoration:none;
}
.navbar-right ul li{
display:inline-block;
list-style-type:none;
border:1px solid #bbb;
padding:5px;
}
.navbar-right li.current-menu-item > a {
color:#fff;
background:#bbb;
/*you can add the active anchor styles here*/
}
<nav class="navbar-right">
<ul>
<li class="current-menu-item">Home</li>
<li class="menu-item">About</li>
<li class="menu-item">Contact</li>
</ul>
</nav>

Today most of the time we have to deal with dropdown menus in wordpress so,just to improvise the above answer, you can use:
add_filter('nav_menu_css_class', 'add_active_class', 10, 2 );
function add_active_class($classes, $item) {
if( $item->menu_item_parent == 0 && in_array('current-menu-item', $classes) ) {
$classes[] = "active";
}
return $classes;
}
you can add active class for child elements using the below code:
add_filter('nav_menu_css_class', 'add_active_class', 10, 2 );
function add_active_class($classes, $item)
{
if( in_array( 'current-menu-item', $classes ) ||
in_array( 'current-menu-ancestor', $classes ) ||
in_array( 'current-menu-parent', $classes ) ||
in_array( 'current_page_parent', $classes ) ||
in_array( 'current_page_ancestor', $classes ))
{
$classes[] = "active";
}
return $classes;
}

I also face the same problem and after searching many page I could only find the solution that I have to set it using jquery code. so I find a unique class addition in my page ".current_page_item" you might have the same or ".current_menu_item" etc.. so just include the following jquery code to your footer and your page will work fine.
$(".current_page_item a").addClass("active");
Do hop this will solve your problem.

You can add "nav-link" class to all anchor tags while having the "active" class on current menu item only by using this code.
/**
* Add CSS class for "<a>" tags in menu
*/
function your_theme_add_menu_link_class( $classes, $item ) {
$classes['class'] = "nav-link"; // Add class to every "<a>" tags
if ( in_array('current_page_item', $item->classes) ) {
$classes['class'] = 'nav-link active'; // Add class to current menu item's "<a>" tag
}
return $classes;
}
add_filter( 'nav_menu_link_attributes', 'your_theme_add_menu_link_class', 10, 2 );

Related

WordPress how to add <span> after main navigation dropdown

I like to add an empty 'span' in the main navigation li element which has a specific class.
Here is the desired look:
<ul>
<li class="menu-item"></li>
<li class="menu-item"></li>
<li class="menu-item has-childern"><span></span></li>
</ul>
I have a code that adds the span after every nav link:
add_filter('nav_menu_item_args', function ($args, $item, $depth) {
if ( $args -> theme_location == 'primary') {
$args -> link_after = '<span></span>';
}
return $args;
}, 10, 3);
How can I achieve to add the 'span' only in the 'li' element which has the 'has-children' class? Thank you for the help!
You could use nav_menu_link_attributes filter hook to get access to the nav attributes.
From Documentation
nav_menu_link_attributes
'after'
(string) Text after the link markup.
'link_after'
(string) Text after the link text.
So you could set it up in multiple ways, for example you could do something like this:
add_filter('nav_menu_link_attributes', 'your_theme_custom_html_element', 10, 3);
function your_theme_custom_html_element($atts, $item, $args)
{
if ($args->theme_location == 'primary' && (strpos($atts['class'], 'has-childern') !== false)) {
$args->after = '<span></span>';
}
return $atts;
}
Just tested on my own website and it works seamlessly fine!

Change sub-menu wrap in Wordpress

In Wordpress, how can I add a button or div into all sub-menu li's using wp_nav_menu?
This is my current code:
<?php wp_nav_menu(array(
'theme_location' => 'main_menu',
'items_wrap'=>'%3$s',
'container' => false
)); ?>
This is my desired output:
<li class="submenu">
<a>Link 1</a>
<ul>
<li><a>Link 2</a></li>
</ul>
<button type="button">Click Me!</button>
</li>
So, Custom Walkers are a bit of a pain to work with, until you understand them.
The below custom walker code should get you what you need. Add this to your theme's functions.php file:
class Custom_Button_Walker extends Walker_Nav_Menu {
// We only care about the "end level" part of the menu, where closing </ul> tags are generated
public function end_lvl( &$output, $depth = 0, $args = array() ) {
// This is from WP core code
$indent = str_repeat("\t", $depth);
// This line ensures we only add it on the proper level
$button = (0 == $depth) ? "{$indent}<button type=\"button\">Click Me!</button>\n" : '';
// This line is modified to include the button markup
$output .= "{$indent}</ul>\n{$button}";
}
}
To use the custom walker, modify your wp_nav_menu call like so:
wp_nav_menu( array(
'theme_location' => 'main_menu',
'items_wrap' =>'%3$s',
'container' => FALSE,
'walker' => new Custom_Button_Walker()
));

Walker class not found error

Hi I am using wordpress for the first time. I am trying to incorperated the walker class into my project which is located at
D:\wamp\www\SgsOnline\wp-content\themes\storefront\inc\functions\walker.php
I've included my class in my functions as
require get_template_directory() . '/inc/functions/walker.php';
And I am trying to call it in my header like :
function storefront_primary_navigation() {
?>
<nav id="site-navigation" class="main-navigation " role="navigation" aria-label="<?php esc_html_e( 'Primary Navigation', 'storefront' ); ?>">
<button class="menu-toggle" aria-controls="primary-navigation" aria-expanded="false"><?php echo esc_attr( apply_filters( 'storefront_menu_toggle_text', __( 'Navigation', 'storefront' ) ) ); ?></button>
<?php
wp_nav_menu(
array(
'theme_location' => 'primary',
'container_class' => 'primary-navigation',
'menu_class'=>'nav navbar-nav navbar-left nav-tabs',
'walker' => new Walker_Nav_Primary()
)
);
?>
</nav><!-- #site-navigation -->
<?php
}
But I am getting a error :
Fatal error: Class 'Walker_Nav_Primary' not found in
D:\wamp\www\SgsOnline\wp-content\themes\storefront\inc\structure\header.php
on line 65
This is oblivious wrong because it is looking in the wrong place for the class.
If anyone has any experience with this would be great
Regards
UPDATE
here is the class code
<?php
/* Collection of walker classes*/
class Walker_Nav_Primary extends Walker_Nav_menu {
function start_lvl( &$output, $depth){ //ul
$indent = str_repeat("\t", $depth );
$submenu = ($depth > 0) 'sub-menu' : ''; //Detect if the lvls is a submenu
$output .= "\n$indent<ul class=\"dropdown-menu$submenu depth_$depth\">\n";
}
/*
function end_lvl(){ // close ul
}
Not used at the moment
function start_el(){ // li, a, span
}
function end_el(){ // closing li, a, span
}
*/
}
At first glance it appears that file path is incorrect. / is unix directory separator but you need to use \ for Windows.
$path_elements = array(get_template_directory(), 'inc', 'functions', 'walker.php');
require join(DIRECTORY_SEPARATOR , $path_elements);
Walker_Nav_Primary has a syntax error in shorthand if-else statement (missing question mark after logical expression).
$submenu = ($depth > 0) ? 'sub-menu' : '';
I believe the issue is how you reference your walker...
'walker' => new Walker_Nav_Primary()
should just be...
'walker' => new Walker_Nav_Primary
no () needed.
If there was an issue with how you include your walker.php file that would error first as functions.php is run before your header.php.

Add `active` class to li of current single page wordpress

Looking for your help and advices.
I have a list of links to single in Wordpress. I need to place class active only to li of active page.
Should be like on this image
But it is:
My wp-code:
<ul class="inline-list medium-6 large-4 skill-items">
<?php
$id = get_the_ID();
// echo $id;
$class;
$skills = new WP_Query( array(
'post_type' => 'skills',
'order' => 'ASC'
));
if ($skills->have_posts()) : while ($skills->have_posts()) : $skills->the_post();
// echo $post->ID;
if( $id == $post->ID) {$class = 'active';} else {$class = '';}
?>
<li class="<?php echo $class; ?>"><?php the_title(); ?></li>
<?php endwhile; endif; wp_reset_query();
?>
</ul>
That's not the proper way to do a menu in Wordpress. You should use wp_nav_menu instead of doing a custom WP_Query.
First, in functions.php add the following to register a new menu:
add_action('after_setup_theme', 'register_my_menu');
function register_my_menu() {
register_nav_menu('skills_menu', __( 'Skills menu', 'your-theme-name' ));
}
Then log in your administration, you will see that new menu placement under Appearance > Menu. Create a new menu for that placement - you have the possibility to automatically add top level new pages to this menu.
Then in your template add the following in order to display the menu:
<?php wp_nav_menu(array('theme_location' => 'skills_menu')); ?>
Wordpress will automatically handle the active class by adding current-menu-item to the appropriate li. No need for any filter for that.
Found an answer for my question using Javascript/jQuery
jQuery(document).ready(function($){
var pgurl = window.location.href;
$("ul.skill-items li").each(function(){
if($(this).find('a').attr("href") == pgurl || $(this).find('a').attr("href") == '' )
$(this).addClass("active");
})
});
pgurl contains your current url. After that for each item we are looking for anchor and its link. Then we are comapring those links, and if their are equal, we add class active to li
You may try this:
function my_alter_classes_on_li( $classes, $item ){
global $post;
if( in_array( $post->post_type, $classes ) ) $classes[] = 'current-menu-item';
return $classes;
}
add_filter( 'nav_menu_css_class', 'my_alter_classes_on_li', 10, 2 );

Want to apply different classes to each selected menu elements

Hi i am having an issues with the customizing of wordpress menu theme. I want to apply different classes on each of the selected menu.
This is exactly what i want.
<ul>
<li class="item1">Home Page</li>
<li class="item2">About Page</li>
<li class="item3">Contact Page</li>
</ul>
When the menu item is clicked different classes would be applied on each of the selected menu item
For example i want to click menu item1 a class active1 should be added to the selected element simillary if i clicked item2 a class active2 should be added to the selected element
This is how i am trying to achieve this but its not working
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class($classes, $item){
if ($item == 'Home Page') {
if( in_array('current-menu-item', $classes) ){
$classes[] = 'active1';
}
}
if ($item == 'Home Page') {
if( in_array('current-menu-item', $classes) ){
$classes[] = 'active2';
}
}
return $classes;
}
Can Anyone please help me? Thanks in Advance
This requires some jQuery
PHP
First, let's construct the menu:
$menu = array(
'1' => 'Home',
'2' => 'About',
'3' => 'contact',
);
PHP/HTML
<ul class="menu">
<?php foreach ($menu as $id => $item): ?>
<li><a class="item item-<?= $id; ?>" href="#"><?= $item; ?></a></li>
<?php endforeach; ?>
jQuery
$(document).ready(function() {
$(document).on('click', '.item', function () {
$('.item').removeClass('active');
$(this).addClass('active');
});
});
After reading more closely I see you want to add the class in PHP. In order for me to answer your question, I need to know how the $classes array looks.

Categories