WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How do I modify wp_nav_menu() link hrefs? (2 posts)

  1. lambeco
    Member
    Posted 3 years ago #

    I'm building a site that will use AJAX or Flash combined deep-linking to display content using WordPress as the CMS. Right now, my wp_nav_menu() output looks like this (I snipped id and class attributes since they aren't relevant):

    <pre><code><div class="menu-header">
    	<ul id="menu-header-navigation" class="menu">
    		<li ...snip...><a href="http://example.tld/">Home</a></li>
    		<li ...snip...><a href="http://example.tld/page-1/">Page 1</a></li>
    		<li ...snip...><a href="http://example.tld/page-2/">Page 2</a></li>
    		<li ...snip...><a href="http://example.tld/page-3/">Page 3</a></li>
    	</ul>
    </div>

    All I want to do is insert "#/" between the domain and the slug, so they look like this:

    <pre><code><div class="menu-header">
    	<ul id="menu-header-navigation" class="menu">
    		<li ...snip...><a href="http://example.tld/">Home</a></li>
    		<li ...snip...><a href="http://example.tld/#/page-1/">Page 1</a></li>
    		<li ...snip...><a href="http://example.tld/#/page-2/">Page 2</a></li>
    		<li ...snip...><a href="http://example.tld/#/page-3/">Page 3</a></li>
    	</ul>
    </div>

    Is there a way I can do this through hooks or something?

    Thanks!

  2. lambeco
    Member
    Posted 3 years ago #

    Found a solution! It requires access to the following PHP functions:
    http://php.net/manual/en/function.parse-url.php
    http://www.php.net/manual/en/function.http-build-url.php

    ...as well as the DOMDocument object.

    Once you have that, add a filter for 'wp_nav_menu_items' with the following:

    function makeDeeplinks($items,$args = null)
    {
    	$dom = new DOMDocument();
    	$dom->loadHTML($items);
    	$linkNodes = $dom->getElementsByTagName('a');
    	$count = $linkNodes->length;
    
    	for($i = 0;$i < $count;$i++)
    	{
    		$node = $linkNodes->item($i);
    		$url = parse_url($node->getAttribute('href'));
    		$url['fragment'] = $url['path'];
    		$url['path'] = '';
    		$node->setAttribute('href',http_build_url(null,$url));
    	}
    	return $dom->saveHTML();
    }

    It basically takes the menu items string, converts it into a DOM object, pulls all the 'a' tags and turns the path into an anchor reference.

Topic Closed

This topic has been closed to new replies.

About this Topic