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:

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:

I also store the update date and insert the credit for Moz in the cached response.

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:

[moz domain="https://example.com"]

This implementation optimizes API usage, improves performance through caching, and provides flexibility with easy-to-use shortcode attributes.

Exit mobile version