Skip to content

Instantly share code, notes, and snippets.

@mattwiebe
Created February 8, 2011 06:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mattwiebe/815998 to your computer and use it in GitHub Desktop.
Save mattwiebe/815998 to your computer and use it in GitHub Desktop.
Clean up the cruft on WP-generated menus
<?php
/**
* De-cruft WordPress-generated menu HTML
* @author Matt Wiebe
* @link http://somadesign.ca/
* @contributor Roger Johansson {@link} http://www.456bereastreet.com/archive/201101/cleaner_html_from_the_wordpress_wp_list_pages_function/
* @license GPL v2 {@link} http://www.opensource.org/licenses/gpl-2.0.php
* @copyright 2011
*/
class SD_Cleaner_Menus {
private static $selected = 'current';
private static $ancestor = 'ancestor';
public static function init() {
add_filter( 'wp_nav_menu', array(__CLASS__, 'cleanup' ) );
add_action( 'wp_head', array(__CLASS__, 'add_permalink_filter'), 100 );
add_filter( 'nav_menu_css_class', array(__CLASS__, 'filter_menu_classes'), 10, 2 );
}
// we add this late so as not to mess up canonical redirects
public static function add_permalink_filter() {
foreach ( array('post', 'page', 'term', 'post_type') as $type )
add_filter( $type . '_link', array(__CLASS__, 'make_root_relative') );
}
public static function filter_menu_classes( $c, $item ) {
$n = array();
if ( in_array('current-menu-item', $c) ) {
$n[] = self::$selected;
}
if ( in_array('current-page-ancestor', $c) ) {
$n[] = self::$selected;
$n[] = self::$ancestor;
}
// fix for root relative URLs
if ( 'custom' === $item->type && 0 === strpos($item->url, '/') ) {
if ( trailingslashit($item->url) === trailingslashit($_SERVER['REQUEST_URI']) ) {
$n[] = self::$selected;
}
}
return $n;
}
public static function cleanup( $menu = '' ) {
if ( empty($menu) )
return $menu;
$menu = self::remove_ids($menu);
$menu = self::remove_title_attributes($menu);
$menu = self::remove_empty_classes($menu);
return $menu;
}
private static function remove_ids($input) {
return preg_replace('/\s*id\s*=\s*(["\']).*?\1/', '', $input);
}
private static function remove_title_attributes($input) {
return preg_replace('/\s*title\s*=\s*(["\']).*?\1/', '', $input);
}
private static function remove_empty_classes($input) {
return str_replace( array(' class=""', " class=''"), '', $input );
}
public static function make_root_relative( $input ) {
return preg_replace('!http(s)?://' . $_SERVER['SERVER_NAME'] . '/!', '/', $input);
}
}
SD_Cleaner_Menus::init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment