WordPress – How To Add Custom URL Parameter Button In Admin Dashboard and Execute Function Call

In this tutorial we will show you how to expand Admin Toolbar in WordPress with a custom URL shortcut with GET parameter, and execute/call custom function code when you click on that URL.

WordPress

WordPress

WordPress Tricks: How To Add Custom URL Parameter, Custom Button In Admin Dashboard and Execute Custom Function Call

First, complete code presented here will be added/appended to your current existing theme’s function.php file that you already use (Twenty Sixteen, Twenty Seventeen, Twenty Eighteen… you get the idea). The reason is because it is the quickest way.

You can always convert it into a stand-alone plugin, of course. In a plugin form it can get some additional features, like custom plugin configuration page, but we need to keep this as simple as possible.

Why All The Trouble?

This is not going to be some random tutorial with dumb example, but an actual fully-applicable code! The reason why we decided to create this modification was because of a static html cache plugin for WordPress, namely Comet Cache (also known as Quick Cache and Zen Cache, before the name changes occurred).

The plugin itself is excellent, however, the (only) one thing that is missing from the free version was the clear cache URL shortcut that we could use, either as a Bookmark in our Web Browser, or as a menu item in Admin Toolbar, when we are logged-in in WordPress backend office. Well, according to the author(s), the above suggestion was fine, but kind-of already covered in the Pro version of the plugin.

Since we were completely satisfied with the basic version, which has so far covered all our needs, the simple URL button shortcut was not something by which we were gonna justify the upgrade.

So, we decided to create our own admin button, also with possibility to be used as a bookmark as well (but it will work only if admin is already logged-in), and use it in almost every page on the site while we browse around.

This alone would boost our productivity while doing modifications and editing our theme and styles, saving big time going into admin dashboard, finding a particular plugin menu/page, and finally – hitting the clear cache button there.

Ok, so let’s get to work!

The entire code is built using only 3 custom PHP functions. All you need is to place them one after another in your theme’s functions.php file before the final closing ?> mark or if your theme does not have the last closing line, even better! You just need to copy the below codes and re-save the file.

FUNCTION 1: Add Custom Button / URL @ WordPress Admin Dashboard

// Admin Toolbar Custom Button
function comet_cache_clear_admin_toolbar_button($wp_admin_bar) {
	$queryParam = (int) '1';
	$queryParamEncoded = urlencode($queryParam);
	$currentUrl = $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
	$reinsertUrlWithParam = add_query_arg('cccclr', $queryParamEncoded, $currentUrl);

	$args = array(
		'id'    => 'comet-cache-custom-clear-button',
		'title' => 'Clear Cache',
		'href'  => $reinsertUrlWithParam,
		'meta'  => array(
			'class' => 'cccclr'
		)
	);
	$wp_admin_bar->add_node($args);
}
add_action('admin_bar_menu', 'comet_cache_clear_admin_toolbar_button', 100);

Effectively, we will achieve this so far:

WordPress How To Add Custom Button In Admin Dashboard Toolbar

WordPress How To Add Custom Button In Admin Dashboard Toolbar

But, this is just a button with appended ?queryParam at the current URL wherever admin is, and it will do absolutely nothing! We need to catch that parameter somehow and call our custom function. While at it, our custom function (shown next) will clear/purge the entire cache directory (all .html files, effectively, but keeping the directory tree structure intact, just as the original Comet Cache built-in Clear command does).

Function “1” is a standard method to inject custom menu item @ Admin Dashboard toolbar.

admin_bar_menu hook = as documented here, a key code that allows us to manipulate our admin toolbar.

$queryParam = you can define your own special param value here, we just use ‘1’ (as ‘true’ or ‘go’). Additionally, in case you use special characters (different from standard latin set and numbers 0-9), we need to urlencode it. Also, we’ve cast variable as integer (int), but if you use letters, you should cast it to (string).

cccclr = is just a name/id of our parameter (cccclr = comet cache custom clear)

FUNCTION 2: Recursive Directory Clear

// Recursive Directory Clear
function recursiveDeleteDir($dir) {
	if (empty($dir)) {
		return;
	}

	$tree = glob(rtrim($dir, '/') . '/*');
	if (is_array($tree)) {
		foreach($tree as $file) {
			if (is_dir($file)) {
				recursiveDeleteDir($file);
			} elseif (is_file($file)) {
				@unlink($file);
			}
		}
	}
}

Not much to say here, as we’ve already covered it in an older article here.

FUNCTION 3: Catching Custom URL Parameter and Executing Custom Function Call

// Custom URL Param Monitoring
function comet_cache_clear_via_url_param() {
	if (current_user_can('administrator')) {
		$queryParam = (int) '1';
		$queryParamDecoded = isset($_GET['cccclr']) ? (int) urldecode($_GET['cccclr']) : '';
		if ($queryParam == $queryParamDecoded) {
			// clear cache
			$dir = COMET_CACHE_DIR;
			recursiveDeleteDir($dir);

			// redirect to remove param
			if (isset($_SERVER['HTTP_REFERER'])) {
				wp_redirect($_SERVER['HTTP_REFERER']);
				exit();
			}
		}
	}
}
add_action('init', 'comet_cache_clear_via_url_param');

This is the final component in our code. First, we need to be sure that only administrator can trigger Clear Cache procedure. Then, we just need to compare our received and decoded custom parameter from URL with the initially defined – and if they match – call our housekeeping function recursiveDeleteDir($dir) with $dir parameter passed as an argument.

One great thing about Comet Cache is that it uses COMET_CACHE_DIR defined constant, which makes our job much easier (because, the path might change in the plugin’s next version, for example). Of course, the name of the constant might change, as well, which would break our code, anyway.

FUNCTION 4: FINAL TOUCH – ADD CUSTOM DASHICON @ WORDPRESS ADMIN TOOLBAR

This function / last step is entirely optional, as it handles icon symbol and mobile view behavior, but it will give you more professional & unified appearance of the Admin Toolbar. If you take a careful look, you will notice that each menu item has it’s own “dashicon” (the official WordPress Icon Font). Now, you probably want to add one such cool icon to your own toolbar item(s). Here is the simplest way how to do it without using external .css file:

// Admin Toolbar Custom Button Icon + Mobile Responsive Button View
function comet_cache_clear_admin_toolbar_button_icon() {
	if(current_user_can('administrator')) {
		// button text
		echo '<style>@media screen and (max-width:782px){#wpadminbar li#wp-admin-bar-comet-cache-custom-clear-button{display:block;}}</style>' . PHP_EOL;
		echo '<style>@media screen and (max-width:782px){#wpadminbar ul li.cccclr{white-space:nowrap; overflow:hidden; width:40px; padding:0; color:#a0a5aa; position:relative;}}</style>' . PHP_EOL;

		// icon symbol
		echo '<style>#wpadminbar .quicklinks>ul>li.cccclr>a.ab-item::before{content:"\f321"; top:3px;}</style>' . PHP_EOL;
		echo '<style>@media screen and (max-width:782px){#wpadminbar ul li.cccclr a.ab-item::before{width:auto;height:46px;line-height:46px;font:40px/1 dashicons !important;}}</style>' . PHP_EOL;
	}
}
add_action('admin_head', 'comet_cache_clear_admin_toolbar_button_icon');
add_action('wp_head', 'comet_cache_clear_admin_toolbar_button_icon');

Notice how we specifically target our li.cccclr menu item class, and manipulate view of the inserted button ID li#wp-admin-bar-comet-cache-custom-clear-button.

A quick word about toolbar responsive design & mobile view: WP core automatically removes all excessive buttons & text content in narrow mobile screens, leaving only large dashicons at first, and removing most of them as the screen width gets progressively smaller. This is done in a bit of an ugly way, actually, using overflow:hidden and fixed .ab-icon element width adjusted to each individual icon(s).

With above code you will display custom dashicon at widths < 782 pixels, and hide button text. This is not ideal, as you might notice some issues with mobile view and different browsers, along with different icons (some CSS rules should be adjusted per each icon, like top position etc.). In order to manipulate things and integrate them well with the core menu icons, you should use wp_enqueue() functions to properly implement this via external CSS instead of in-page injected one, but that is up to you.

Also, you will probably want to change that f321 icon ID code with your own choice (full list of available WordPress dash icons).

If you do not care about accessibility of the custom menu button @ mobile, you may completely forget about 4th function above.

WordPress Nonce In URL with Parameters

For completeness, we can also add nonce code to protect users against unintentional triggering of the action (when, for example, admin or editor previously logged-in clicks on specially crafted malware links that target their websites):

$url = "website.com/?action=cccclr"; // construct action url
$action = "custom-cache-clear"; // define action name
$link = wp_nonce_url($url, $action); // generate WordPress nonce code
echo '<a href="' . $link . '">Clear Cache</a>'; // construct & echo ahref link

We must also incorporate nonce argument check in our 3rd function below, here is just a small code snippet:

function comet_cache_clear_via_url_param() {
	if (current_user_can('administrator')) {
		if (isset($_GET['action']) && $_GET['action'] == 'cccclr') {
			check_admin_referer('custom-cache-clear'); // die if invalid or missing nonce

			// REST OF FUNCTION 3 CODE HERE
		}
	}
}
}

However, we will not use that method here, simply because it will prevent us from our initial requirement to use it as a regular browser bookmark (because, nonce has a limited validity period and changes dynamically over time!).

Again, if you wish to avoid potential harm, the parameter ID must be unique and hard to guess, and also – do not click on suspicious or obfuscated links in the first place (although, some advanced XSRF attacks do not require any “physical” clicks from the user input, all they need to do is load some HTML elements, like images, and they will automatically trigger malicious action!).

 

CONCLUSION

This is the end of our tutorial. Of course, the code can be improved. For example, we could use or extend existing classes from the plugin to build the custom shortcut feature, but this is much simpler way that everyone can understand how it works and what is going on.

WordPress - How To Add Custom Dashicon Button In Admin Dashboard Toolbar (Desktop View)

WordPress – How To Add Custom Dashicon Button In Admin Dashboard Toolbar (Desktop View)

For simplicity reasons, we are not checking if the plugin is available and active (we assume that we are using this accompanying code along the plugin), but it could be done with some additional conditions and checks where we currently are (backend or frontend), or if the site operates in multisite mode (it may work just fine, but we haven’t checked it).

WordPress - How To Add Custom Dashicon Button In Admin Dashboard Toolbar (Mobile View)

WordPress – How To Add Custom Dashicon Button In Admin Dashboard Toolbar (Mobile View)

Finally, for your custom code you should rename all occurrences of ‘cccclr’ parameter name (yes, with single quotes!) with your own (or random) parameter name (for example: ‘xlr12345’). This way, if someone tries to guess it will be very hard, but even if they guess it they will be redirected to the admin login page, because of administrator condition we’ve placed early into the code.

Comments


  1. comments

    2 Comments

    Add Your Comment
  2. 1. Raam Dev

    Instead of calling a custom recursiveDeleteDir() function to clear the cache, you could just use the Comet Cache API and call comet_cache::clear(). The Lite (free) version of Comet Cache includes access to the most of the API calls. You can see a full list of Comet Cache API calls in this KB article: Clearing the Cache Dynamically

  3. 2. TehnoBlog (In reply to Raam Dev)

    Thanks Raam Dev, really appreciate your help!

Post A Comment

I have read and consent to Privacy Policy and Terms and Conditions