[SOLVED] Add class to existing function

Post Reply
alexvf
Posts: 2
Joined: Tue Apr 10, 2018 4:15 pm

[SOLVED] Add class to existing function

Post by alexvf »

Hi,

For me to be able to use Bootstrap 4.0 among other things I need to add classes to the navigation <li>s.

To do this I need to change the menu() function from this:

Code: Select all

public static function menu()
	{
		$output = '';
		foreach (wCMS::get('config', 'menuItems') as $key => $value) {
			if ($value->visibility == "hide") {
				continue;
			}
			$output .= '<li' . (wCMS::$currentPage === $value->slug ? ' class="active"' : '') . '><a href="' . wCMS::url($value->slug) . '">' . $value->name . '</a></li>';
		}
		return wCMS::hook('menu', $output)[0];
	}
to this

Code: Select all

public static function menu()
	{
		$output = '';
		foreach (wCMS::get('config', 'menuItems') as $key => $value) {
			if ($value->visibility == "hide") {
				continue;
			}
			$output .= '<li class="nav-item nav-link' . (wCMS::$currentPage === $value->slug ? ' active"' : '"') . '><a href="' . wCMS::url($value->slug) . '">' . $value->name . '</a></li>';
		}
		return wCMS::hook('menu', $output)[0];
	}
But I don't want to change the index.php file.

Is there a way for me to do this using a function in functions.php that overrides the menu() function in index.php?
Or is there any other way to do this without touching the index.php file?

Thanks in advance for your help.
Cheers.
wiz
Admin
Posts: 481
Joined: Sat Oct 30, 2010 12:23 am

Re: Add class to existing function

Post by wiz »

Managed to squeeze some time to check this out.
There is no "elegant" way of solving this with PHP. This issue can be solved with jQuery (Javascript library which is already included in WonderCMS).

Quick tutorial:
1. Create a addNavClasses.js file in your theme folder and include it in your theme.php (in the <head></head> tags)

Code: Select all

<script src="<?=wCMS::asset('addNavClasses.js')?>"></script>
2. Paste the below content inside your addNavClasses.js file:

Code: Select all

$( document ).ready(function() {
    $("nav > li").addClass('nav-item nav-link');
});
The above code should in theory add class="nav-item nav link" to your <li>'s.

I haven't managed to test this out, please spin it for a test and let me know.
Post Reply