将下面代码添加加到主题函数模板functions.php中。

1Section

添加自定义文字


  1. add_filter( 'wp_nav_menu_items', 'zm_custom_menu_item', 10, 2 );

  2. function zm_custom_menu_item ( $items, $args ) {

  3. if ( $args->theme_location == 'navigation') {// navigation为菜单名称

  4. $items .= '<li><a title="">自定义文字</a></li>';

  5. }

  6. return $items;

  7. }

怎么找到主题注册的名称呢?在主题源代码找有些麻烦,可以在菜单设置页面,在菜单设置→位置,使用浏览器开发工具查看源代码,比如:

image.png

其中带【】部分就是,以下相同。

2Section

在菜单添加当前日期

  1. add_filter('wp_nav_menu_items','zm_add_todaysdate_in_menu', 10, 2);

  2. function zm_add_todaysdate_in_menu( $items, $args ) {

  3. if( $args->theme_location == 'navigation')  {

  4. $todaysdate = date('Y-m-d');

  5. $items .=  '<li><a>' . $todaysdate .  '</a></li>';

  6. }

  7. return $items;

  8. }

3Section

在菜单添加显示登录用户名

  1. add_filter( 'wp_nav_menu_objects', 'zm_username_menu_items' );

  2. function zm_username_menu_items( $menu_items ) {

  3. foreach ( $menu_items as $menu_item ) {

  4. if ( strpos($menu_item->title, '#profile_name#') !== false ) {

  5. if ( is_user_logged_in() ) {

  6. $current_user = wp_get_current_user();

  7. $user_public_name = $current_user->display_name;

  8. $menu_item->title =  str_replace("#profile_name#",  " 您好, ". $user_public_name, $menu_item->title . "!");

  9. } else {

  10. $menu_item->title =  str_replace("#profile_name#",  " 您好!", $menu_item->title . "!");

  11. }

  12. }

  13. }

  14.    return $menu_items;

  15. }

需要在菜单添加一个自定义链接,然后将”导航标签“一栏改为#profile_name#

4Section

带链接的按钮

  1. function zm_add_button_menu_link($items, $args){

  2. if( $args->theme_location == 'primary' ){

  3. $items .= '<li class="menu-item"><a class="btn btn-primary" title="自定义按钮" href="#">自定义按钮</a></li>';

  4. }

  5. return $items;

  6. }

  7. add_filter( 'wp_nav_menu_items', 'zm_add_button_menu_link', 10, 2 );

为什么不用菜单自带的自定义链接,因为上述方法可以定制链接按钮的class结构。