Here’s a handy line of code that will enable you to place a button which only administrators can see virtually anywhere on your WordPress site.
As usual with these code snippets I’m going to divide the process into the parts: php, HTML and CSS.
Here’s want we want to do in text “If the current user has the mange options capability then display the link button.” so lets write the function in php (and HTML).
function show_links() { if( current_user_can( 'manage_options' ) ) echo "<div class='link-btn'><a href='http://example.url'>LINKS</a></div>"; }
The WordPress function current_user_can checks the capabilities (or access levels) of the user looking at the page and returns a boolean true or false result depending on whether the user has the ‘manage_options’ capability (or access level clearance).
You could use a different capabilities such as ‘read’ to show the button to all logged in users, check the list of different capabilities and the user groups they apply to on the WordPress site for the full rundown.
The ‘echo’ statement will only run when the user has the capability to ‘manage options’, which only admin level users have. You can edit the HTML inside the double quotes [“] – making sure you only use single quotes. I’ve gone for a little div with the class ‘link-btn’ holding the txt link.
This function is then placed into the current theme’s functions.php file, preferably with some nice commenting.
I’m going to place this button one on the top right in the header, so firstly I find the header.php file from the current theme and (which would a be a child theme – something I’ll write about very soon!) insert the following statement in a likely looking spot, in this case just after the html tag opens.
<?php show_links(); ?>
A quick glance at the homepage will confirm you now have a button that says links in your header, so for the finishing touch it’s to the stylesheet for a bit of css.
.link-btn { float: right; display: block; text-align:center; } .link-btn a { display: block; width: 125px; padding: 5px 10px; color: #000; font-family: Helvetica, Calibri, Arial; font-size: 14px; font-weight: bold; background-color: #c9c9c9; border: 1px solid #333; border-radius: 5px; } .link-btn a:hover { color: white; background-color: #333; border-color: #c9c9c9; }
I suspect you will need to edit the CSS to get a nice fit with your site, however using the simple guide and remembering to insert your url into the link at the top and edit the css you can have a nice button for admin users only on your site within a couple of minutes!
Good News eh!