kiarashi kiarashi - 1 year ago 107
PHP Question

preg_replace wp menu item

Need a bit of help with

inside wordpress.

My source code is like this

<li id="menu-item-98" class="navigation-heading menu-item menu-item-type-custom menu-item-object-custom menu-item-98">
<a href="#">Main</a>

By using
, I'd like to change it to the following html markup below whenever the
tag has the

<div class="navigation-heading">
<span><a href="#">Main</a></span>

If someone could help me out with my code below, I'd greatly appreciate it.

function add_nav_class($output) {
$output= preg_replace('...', '...', $output, 1);
return $output;
add_filter('wp_nav_menu', 'add_nav_class');

Answer Source

This seems relatively straightforward and likely doesn't need to be complex at all. Basically, you can just capture everything inside the <li> tags and then plug that in to your replacement string.

In its simplest form, it'd just be this:


But if it were me, I'd probably just remove the extra spaces around the match by adding in \s* before and after the capture group.


Well, anyway, once you have your match captured, you can just fill out the text around the $1 like this:

<div class="navigation-heading">\n<span>\n    <span>$1</span>\n</span>\n</div>

That should be all you need to kick this thing in the drive.

Here is a demo of the REGEX

Here is a demo of it in PHP

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download