WordPress Admin Bar Custom Link – In this post we see how we can add custom links to admin bar. Sometimes when we work with plugins or theme and we need to add some link or any information in admin bar at the top then we can use this code snippet to create the same.
As we know WordPress provide hooks using which we can easily add custom data with default one. So, for this we’ll use ‘admin_bar_menu’ hook and add action to this hook –
<?php /* * @author Webkul */ add_action( 'admin_bar_menu', 'wk_custom_admin_bar_link', 100 ); ?>
In above line of code, first parameter is the hook we discuss about, second one is callback function and last is position of custom link will be added using this.
<?php function wk_custom_admin_bar_link( $admin_bar ) { $admin_bar->add_menu( array( 'id' => 'wp-custom-link', 'title' => 'Custom Item', 'href' => admin_url(), 'meta' => array( 'title' => __('Custom'), ), )); } ?>
In above function, we used the method of $wp_admin_bar global which works only during ‘admin_bar_menu’ hook. In this methos we provide some arguments like id, title, href, and meta arguments for custom link we are creating. There are some more arguments also which can be used like in meta we can provide class, rel, target, etc. All possible options can be explore here .
We can also add sub items to this custom link and can make this dropdown. This can be done by creating child to this link, which can be achieved by setting id of parent in parent argument while creating child node. Let’s see –
<?php function wk_custom_admin_bar_link( $admin_bar ) { $admin_bar->add_menu( array( 'id' => 'wp-custom-link', 'title' => 'Custom Item', 'href' => admin_url(), 'meta' => array( 'title' => __('Custom'), ), )); $admin_bar->add_menu( array( 'id' => 'wp-sub-link', 'parent'=> 'wp-custom-link', 'title' => 'Sub Item', 'href' => admin_url(), 'meta' => array( 'title' => __('Sub Item'), ), )); } ?>
We can see in below image that Sub-Item link added as the child of Custom Item.
Reference – https://codex.wordpress.org/Class_Reference/WP_Admin_Bar .
Support
Still have any issue feel free to add a ticket and let us know your views to make the code better https://webkul.uvdesk.com/en/customer/create-ticket/
Thanks for Your Time! Have a Good Day!
2 comments
Thanks for the valuable words.
Keep in tune for more such informative content. If you have any query kindly feel free to share it on [email protected].
Thanks and Regards.