Posted By

SFLWebDev on 08/12/12



Versions (?)

WordPress WP Nav Menu Custom HTML ID Based on Page or Category Titles

 / Published in: PHP

This function, when placed in a theme's 'functions.php' file will insert a custom id attribute into the '

  • ' elements generated by a 'wpnavmenu' function based on the title of the element. It will make a WordPress page or category into a hyphen separated string for CSS styling.

    For example, if a post category has the name "This & That", it will generate an HTML id attribute as "this-that".

    This version replaces spaces and ampersands - other characters can be added to the "strreplace" functions to filter out other characters that may exist in the "$itemdetails>title" property.

    1. add_filter('nav_menu_item_id','change_nav_menu_id',10,2);
    2. function change_nav_menu_id($current_id,$item_details){
    3. global $menu_counter;
    5. $id_slug = strtolower(str_replace(' ', '-', $item_details->title));
    6. $id_slug = strtolower(str_replace('&', '',$id_slug ));
    7. $id_slug = strtolower(str_replace('--', '-',$id_slug ));
    9. return $id_slug;
    10. }

    Report this snippet  

    You need to login to post a comment.