To modify the WordPress menu items, you can use the wp_nav_menu_items
filter in your theme’s functions.php
file. The following code snippet will add a new menu item to the primary
menu:
function wpsnippets_menu_items ( $items, $args ) {
if ($args->theme_location == 'primary') {
$items .= '<li><a href="' . esc_url( home_url( '/custom-page' ) ) . '">Custom Page</a></li>';
}
return $items;
}
add_filter('wp_nav_menu_items', 'wpsnippets_menu_items', 10, 2);
This code adds a new menu item to the primary menu by appending HTML code to the existing menu items. The site_url()
function is used to generate the URL of the custom page, and this URL is included in the href
attribute of the new menu item. You can modify the site_url('/custom-page')
part of the code to use the URL of the page you want to link to.
If you want to remove an existing menu item, you can use a similar approach:
function wpsnippets_remove_menu_item( $items, $args ) {
if ($args->theme_location == 'primary') {
$items = str_replace( '<menu-item-html>, '', $items );
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'wpsnippets_remove_menu_item', 10, 2 );
This code uses the str_replace()
function to replace the HTML code for a specific menu item with an empty string. You can modify the <menu-item-html>
part of the code to match the HTML code for the menu item you want to remove.