Skip to content

Instantly share code, notes, and snippets.

@mattheu
Last active August 29, 2015 13:56
Show Gist options
  • Save mattheu/9093265 to your computer and use it in GitHub Desktop.
Save mattheu/9093265 to your computer and use it in GitHub Desktop.
Replace wp nav menu links that have just a hash url with headings
<?php
/*
Plugin Name: Nav Menu Headings
Plugin URI: https://gist.github.com/mattheu/9093265
Description: Add headings to nav menus
Author: Matth.eu
Version: 0.1-alpha
Author URI: http://matth.eu
Text Domain: nav-menu-headings
Domain Path: /lang
*/
/**
* Replace menu links with a hash url with headings.
*/
add_filter( 'walker_nav_menu_start_el', function( $item_output, $item ) {
if ( ! isset( $item->url ) || $item->url !== "#" )
return $item_output;
$dom = new DOMDocument();
@$dom->loadHTML( $item_output );
foreach ( $dom->getElementsByTagName('body')->item(0)->childNodes as $node ) {
if ( '#' !== $node->getAttribute('href') )
continue;
// Create new element.
$new_node = $dom->createElement('h4');
// Copy children.
while ( $node->childNodes->length > 0 )
$new_node->appendChild( $node->childNodes->item(0) );
// Copy attribute
foreach ( $node->attributes as $attr )
$new_node->setAttribute( $attr->nodeName, $attr->nodeValue );
// Remove link specific attributes.
$new_node->removeAttribute( 'href' );
$new_node->removeAttribute( 'target' );
// Set a new class
$new_node->setAttribute( 'class', $new_node->getAttribute( 'class' ) . ' menu-heading' );
$node->parentNode->replaceChild( $new_node, $node );
}
$r = '';
foreach ( $dom->getElementsByTagName('body')->item(0)->childNodes as $node )
$r .= $dom->saveHtml( $node );
return $r;
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment