在 WordPress 导航菜单添加自定义文字信息,将下面代码添加加到主题函数模板 functions.php 中。
添加自定义文字
- add_filter( 'wp_nav_menu_items', 'zm_custom_menu_item', 10, 2 );
- function zm_custom_menu_item ( $items, $args ) {
- if ( $args->theme_location == 'navigation') {// navigation为菜单名称
- $items .= '<li><a title="">自定义文字</a></li>';
- }
- return $items;
- }
怎么找到主题注册的名称呢?在主题源代码找有些麻烦,可以在菜单设置页面,在菜单设置→位置,使用浏览器开发工具查看源代码,比如:
其中带【】部分就是,以下相同。
在菜单添加当前日期
- add_filter('wp_nav_menu_items','zm_add_todaysdate_in_menu', 10, 2);
- function zm_add_todaysdate_in_menu( $items, $args ) {
- if( $args->theme_location == 'navigation') {
- $todaysdate = date('Y-m-d');
- $items .= '<li><a>' . $todaysdate . '</a></li>';
- }
- return $items;
- }
在菜单添加显示登录用户名
- add_filter( 'wp_nav_menu_objects', 'zm_username_menu_items' );
- function zm_username_menu_items( $menu_items ) {
- foreach ( $menu_items as $menu_item ) {
- if ( strpos($menu_item->title, '#profile_name#') !== false ) {
- if ( is_user_logged_in() ) {
- $current_user = wp_get_current_user();
- $user_public_name = $current_user->display_name;
- $menu_item->title = str_replace("#profile_name#", " 您好, ". $user_public_name, $menu_item->title . "!");
- } else {
- $menu_item->title = str_replace("#profile_name#", " 您好!", $menu_item->title . "!");
- }
- }
- }
- return $menu_items;
- }
需要在菜单添加一个自定义链接,然后将”导航标签“一栏改为#profile_name#
带链接的按钮
- function zm_add_button_menu_link($items, $args){
- if( $args->theme_location == 'primary' ){
- $items .= '<li class="menu-item"><a class="btn btn-primary" title="自定义按钮" href="#">自定义按钮</a></li>';
- }
- return $items;
- }
- add_filter( 'wp_nav_menu_items', 'zm_add_button_menu_link', 10, 2 );
为什么不用菜单自带的自定义链接,因为上述方法可以定制链接按钮的 class 结构。
- 1、本站大部分内容均收集于网络,若内容侵犯到您的权益,请发送邮件至:service@wuyanshuo.cn,我们将第一时间处理!
- 2、本站资源所需价格并非资源售卖价格,是收集、整理、编辑以及本站运营的适当补贴,并且本站不提供任何免费技术服务。
- 3、所有资源仅限参考和学习,版权归原作者所有,更多请阅读无言说网络服务器协议。