
Using Hooks to Add Links in WordPress Menu
- August 3, 2016
- Leave a comment
WordPress provides us with many useful hooks (filters) for different actions. To use them, the content of a particular function’s output needs to be modified. This article includes steps that will help you add menu links and display Login/Logout links in the WordPress menu.
To add links by the name of wp_nav_menu function in PressTigers WordPress menu, you would need to use the wp_nav_menu_items hook. Now attach this hook with pt_add_menu_links function.
The following code will first check the menu name. If the menu name matches the desired menu to which you want to add links, it will do so and merge the new links with those that already exist. Let us assume that the menu name is “main menu”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php function pt_add_menu_links( $items, $args ){ $menu_obj = $args->menu; // verify if the menu is being called is our required menu to which we have to add links if( ( is_object( $menu_obj ) && $menu_obj->name === 'Main Menu' ) || ( is_string( $menu_obj ) && $menu_obj === 'Main Menu' ) ){ // checking if user if logged-in if( is_user_logged_in() ){ $new_links = '<li><a href="'.esc_url( home_url( '/my-account/' ) ).'">'.__( 'My Account', 'text-domain' ).'</a></li>'; $new_links .= '<li><a href="'.esc_url( home_url( '/logout/' ) ).'">'.__( 'Logout', 'text-domain' ).'</a></li>'; } // if user is not logged-in else{ $new_links = '<li><a href="'.esc_url( home_url( '/login/' ) ).'">'.__( 'Login', 'text-domain' ).'</a></li>'; } // merge menu links and new links $items = $items . $new_links; } return $items; } // attach function(pt_add_menu_links) with wordpress nav menu hook for items add_filter( 'wp_nav_menu_items', 'pt_add_menu_links', 10, 2 ); ?> |
User Comments