![](/img/trans.png)
[英]how to add data attribute to a specific <li> element in wordpress nav menu
[英]WordPress: add HTML to a specific nav menu
add_filter('wp_nav_menu_items', 'add_custom', 10, 2);
function add_custom($items, $args) {
if ($args->theme_location == 'primary') {
$items .= '<li class="custom"></li>';
}
return $items;
}
產生:
<ul id="menu-top">
<li></li>
<li></li>
<li></li>
<li class="custom"></li> /* added custom HTML */
<ul>
但是,如果我的WP菜單沒有“ theme_location”怎么辦? 我可以按ID /類而不是“ theme_location”定位菜單,還是可以將HTML添加到一個特定菜單?
可以使用jQuery嗎?
jQuery(document).ready(function($) {
$('#menu-top').append('<li class="custom"></li>');
});
或PHP + CSS-使用此解決方案,您可以將其添加到每個菜單中,並在需要時通過CSS隱藏它。
add_filter('wp_nav_menu_items', 'add_custom', 10, 2);
function add_custom($items, $args) {
$items .= '';
return $items;
}
li.custom { display:none; } // hide originally
ul#menu-top li.custom { display:inline; } // or whatever styles
當沒有theme_location時,我想,它會退回到wp_page_menu。 因此,從理論上講,您可以過濾到wp_page_menu
並修改輸出。
<?php
//Use this filter to modify the complete output
//You can get an argument to optionally check for the right menu
add_filter( 'wp_page_menu', 'my_page_menu', 10, 2 );
/**
* Modify page menu
* @param string $menu HTML output of the menu
* @param array $args Associative array of wp_page_menu arguments
* @see http://codex.wordpress.org/Function_Reference/wp_page_menu
* @return string menu HTML
*/
function my_page_menu( $menu, $args ) {
//see the arguments
//Do something with $menu
return $menu;
}
//Use this filter to alter the menu argument altogether
//It is fired before creating any menu html
add_filter( 'wp_page_menu_args', 'my_page_menu_pre_arg', 10, 1 );
/**
* Modify page menu arguments
* @param array $args Associative array of wp_page_menu arguments
* @see http://codex.wordpress.org/Function_Reference/wp_page_menu
* @return array modified arguments
*/
function my_page_menu_pre_arg( $args ) {
//Do something with $args
return $args;
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.