Last active
October 7, 2016 23:15
-
-
Save Phoenix2k/f0d4082af8427ab4cfd80b01f44ab8dc to your computer and use it in GitHub Desktop.
WordPress: Nav menu hacks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Add custom attributes to WP nav menu links | |
*/ | |
add_filter( 'nav_menu_link_attributes', 'nav_menu_link_attributes_override', 10, 3 ); | |
function nav_menu_link_attributes_override( $atts, $item, $args ) { | |
// Use an identifier like a hashtag to grab the ones you want to override | |
if ( 'custom' === $item->type && ( preg_match( '/^#/', $item->url ) ) ) { | |
// Get value after the hashtag | |
$value = substr( $item->url, 1 ); | |
// Do something with it | |
// You can also search for a specific value and replace it with something else | |
$search_and_replace = array( | |
'#logout' => wp_logout_url() | |
); | |
foreach ( $search_and_replace as $search => $replace ) { | |
if ( $atts[ 'href' ] === $search ) { | |
$atts[ 'href' ] = str_replace( $search, $replace, $atts[ 'href' ] ); | |
break; | |
} | |
} | |
} | |
return $atts; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Search and replace titles from WP nav menu links | |
*/ | |
add_filter( 'nav_menu_item_title', 'nav_menu_item_title_override', 10, 3 ); | |
function nav_menu_item_title_override( $title ) { | |
$search = '{{ keyword }}'; | |
if ( false !== strpos( $title, $search ) ) { | |
$replace = 'Replace keyword with this'; | |
$title = str_replace( $search, $replace, $title ); | |
} | |
return $title; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment