Moz: Create A WordPress Shortcode To Publish Your Site Authority and Metrics
When companies review sites to write articles on, they often look for sites with high domain authority, indicating solid ranking and traffic from search engines. One leader, of course, in the SEO industry is Moz. For my site, I hoped to take some of the information from Moz’s collected data and publish it on my Media Kit page.
Moz has a great API that allows you to pull this information from their service, and they even offer a free tier of their API that allows 50 requests per month. So, I built a nice shortcode for WordPress that publishes the stats and caches the response for 24 hours so that you’re not constantly hitting their API and burning up their limits.
Moz Results for Martech Zone
Here are the results:
- Page Authority: 51
- Domain Authority: 58
- Spam Score: 1%
- Root Domains to Root Domain: 11,430
- External Pages to Root Domain: 1,584,894
- Last Updated: Jan 18, 2025 from Moz
Here’s the shortcode that I used to produce that content.
[moz domain="https://martech.zone"]
Moz requires you to credit them with a direct link to their primary domain. It can be a nofollow link, but they require credit for all published data.
Moz Site Metrics Explained
The API call returns:
- Page Authority: A score developed by Moz that predicts how well a specific page will rank on search engine result pages (SERPs). Scale: 0 to 100 (higher is better). Helps evaluate the strength of a specific page on a website compared to others.
- Domain Authority: A score that predicts the ranking potential of an entire domain or subdomain. Scale: 0 to 100 (higher is better). This is useful for comparing one domain’s strength against another and understanding its overall visibility on search engines.
- Spam Score: Measures the likelihood of a domain being spammy based on factors like thin content, poor linking practices, or poor neighborhood associations. Scale: 1% to 100% (lower is better). This helps identify potential risks when linking to a domain or improving your own domain’s credibility.
- Root Domains to Root Domain: Represents the number of unique root domains (websites) that link to the root domain being analyzed. Example: If
example.com
is linked bysite1.com
andsite2.com
, the count is 2. More linking root domains often correlate with better domain authority and rankings. - External Pages to Root Domain: Indicates the number of external pages linking to the root domain being analyzed. Example: If
page1.html
andpage2.html
fromsite1.com
link to your root domain, the count increases. Measures the number of external backlinks pointing to the domain, which strongly indicates link popularity.
I also store the update date and insert the credit for Moz in the cached response.
- Last Updated: The timestamp of the domain’s most recent Moz API request. Indicates the freshness of the metrics data, ensuring you’re not working with outdated information.
WordPress Shortcode Plugin for Moz Site Metrics
Here’s the code for the plugin. You’ll notice that you can either hardcode your token or add it to the shortcode attribute. If you’re testing, I’ve also added a refresh variable for testing ($moz_refresh_cache
). If it’s set to true, it will bypass the cache and request with each page request.
To use it, create a folder in your plugins directory moz-shortcode
and paste this code into a page moz-shortcode.php
page within it. Activate the plugin and add your shortcode on the pages you wish to display the data on.
<?php
/**
* Plugin Name: Moz Metrics Shortcode
* Description: A shortcode to display domain site metrics from the Moz API with caching, default token, and "Last Updated" date.
* Version: 1.7
* Author: Douglas Karr
* Author URl: https://dknewmedia.com
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly.
}
// Define default Moz API token
define('DEFAULT_MOZ_API_TOKEN', 'your-default-moz-api-token');
// Define refresh setting (true to force refresh, false to use cached data)
$moz_refresh_cache = false; // Set to true to force refresh during development or debugging
// Register the shortcode
function moz_metrics_shortcode($atts) {
global $moz_refresh_cache;
// Extract attributes
$atts = shortcode_atts(
[
'token' => DEFAULT_MOZ_API_TOKEN, // Use the default token if none is provided
'domain' => '',
],
$atts,
'moz'
);
$moz_token = sanitize_text_field($atts['token']);
$domain = sanitize_text_field($atts['domain']);
if (empty($domain)) {
return '<p>Domain cannot be empty. Please specify a domain.</p>';
}
// Determine the cache file path
$plugin_dir = plugin_dir_path(__FILE__);
$domain_hash = get_normalized_domain_hash($domain);
$cache_file = get_cache_file_path($domain);
// Check if cache file exists and is not expired
$cache_exists = file_exists($cache_file);
$cache_valid = $cache_exists && (time() - filemtime($cache_file)) < DAY_IN_SECONDS;
if ($moz_refresh_cache || !$cache_valid) {
// Refresh the cache by making an API call
$api_url = 'https://api.moz.com/jsonrpc';
$api_request = [
'jsonrpc' => '2.0',
'id' => bin2hex(random_bytes(16)), // Generates a unique 32-character ID
'method' => 'data.site.metrics.fetch',
'params' => [
'data' => [
'site_query' => [
'query' => $domain,
'scope' => 'domain',
],
],
],
];
$response = wp_remote_post($api_url, [
'headers' => [
'x-moz-token' => $moz_token,
'Content-Type' => 'application/json',
],
'body' => wp_json_encode($api_request),
]);
if (!is_wp_error($response)) {
$response_body = wp_remote_retrieve_body($response);
$response_data = json_decode($response_body, true);
if (!isset($response_data['error']) && isset($response_data['result']['site_metrics'])) {
// Write data to the cache file
$metrics = $response_data['result']['site_metrics'];
$last_updated = current_time('timestamp'); // Current timestamp based on WordPress settings
$cache_content = [
'metrics' => $metrics,
'last_updated' => $last_updated,
];
file_put_contents($cache_file, json_encode($cache_content));
}
}
}
// Read cached data
if (file_exists($cache_file)) {
$cache_content = json_decode(file_get_contents($cache_file), true);
$metrics = $cache_content['metrics'];
$last_updated = $cache_content['last_updated'];
} else {
return '<p>Unable to retrieve metrics. (Cache file missing or invalid).</p>';
}
// Format the date for "Last Updated"
$last_updated_date = date_i18n(get_option('date_format'), $last_updated);
// Parse and format the results
ob_start();
?>
<ul>
<li><strong>Page Authority:</strong> <?php echo esc_html($metrics['page_authority']); ?></li>
<li><strong>Domain Authority:</strong> <?php echo esc_html($metrics['domain_authority']); ?></li>
<li><strong>Spam Score:</strong> <?php echo esc_html($metrics['spam_score']); ?>%</li>
<li><strong>Root Domains to Root Domain:</strong> <?php echo esc_html(number_format($metrics['root_domains_to_root_domain'])); ?></li>
<li><strong>External Pages to Root Domain:</strong> <?php echo esc_html(number_format($metrics['external_pages_to_root_domain'])); ?></li>
<li><strong>Last Updated:</strong> <?php echo esc_html($last_updated_date); ?> from <a href="https://moz.com" rel="nofollow" target="_blank">Moz</a></li>
</ul>
<?php
return ob_get_clean();
}
add_shortcode('moz', 'moz_metrics_shortcode');
// Function to normalize a domain and return its md5 hash
function get_normalized_domain_hash($domain) {
$normalized_domain = strtolower(trim($domain));
$normalized_domain = preg_replace('/^https?:\/\//', '', $normalized_domain); // Remove http:// or https://
$normalized_domain = preg_replace('/^www\./', '', $normalized_domain); // Remove 'www.'
$normalized_domain = rtrim($normalized_domain, '/'); // Remove trailing slashes
return md5($normalized_domain); // Return the md5 hash of the normalized domain
}
// Function to get the cache file path
function get_cache_file_path($domain) {
// Get the hash of the normalized domain
$domain_hash = get_normalized_domain_hash($domain);
// Determine the cache directory path (one level up from the plugin directory)
$plugin_dir = plugin_dir_path(__FILE__);
$cache_dir = dirname($plugin_dir) . '/cache';
// Create the cache directory if it doesn't exist
if (!file_exists($cache_dir)) {
wp_mkdir_p($cache_dir); // Creates the directory recursively
}
// Return the full cache file path
return trailingslashit($cache_dir) . 'moz_cache_' . $domain_hash . '.html';
}
Explanation of the Code
The shortcode fetches and displays SEO metrics for a specified domain using the Moz API. Here’s how the code works:
- Shortcode Attributes:
token
: The Moz API token. Defaults to a predefined token if not provided.domain
: The domain for which metrics are retrieved. This is a required attribute and requires thehttps://
refresh
: Optional. Set totrue
to force refresh the cached data and make a fresh API call.
- Caching:
- I modified the cache actually to save a file in a cache directory based a unique hash of the domain.
- If the
refresh
variable is set totrue
, the cache is cleared and updated with fresh data.
- Error Handling:
- If the API call fails or returns an error, appropriate error messages are displayed without caching invalid data.
- If no domain is provided, a message is shown, and the API call is skipped.
- Customization:
- The metrics are displayed as an unordered list (
<ul>
), formatted for readability. - The “Last Updated” field ensures users know when the data was last refreshed.
- The metrics are displayed as an unordered list (
- Usage Examples:
- Fetch and displays cached metrics for the specified domain.
[moz domain="https://example.com"]
This implementation optimizes API usage, improves performance through caching, and provides flexibility with easy-to-use shortcode attributes.