0

I am trying to set up a shortcode that will fetch Moz API data but I am facing issues. Sometimes, it returns values to 0, and sometimes it works. I don't know what I am doing wrong here. Might be I need to delete the existing transients or to check if value = 0 in transients. Further, I am using the same code for retrieving different MOZ API data by rewriting this function using different transient keys. Can I merge this code into one? Like [moz_score_da] and [moz_score_pa] Here is the code: The major issue is that I am stuck with some transient values returning zero and then I have to delete them manually and it pulls back the correct value.

I am using this shortcode in the ACF field. If possible, kindly guide me If I can directly update the acf field using transients and shortcodes.

function post_title_shortcode(){
    return get_the_title();
}
add_shortcode('post_title','post_title_shortcode');


function moz_score_shortcode($atts) {
    extract(
        shortcode_atts(
            array(
                'domain' => get_the_title(),
            ),
            $atts
        )
    );

    if ( ! $domain )
        return; // No domain, nothing to return

    $cache_key = 'agency_moz_score_' . $domain;
    if ( false === $seo_grade = get_transient( $cache_key ) ) {
        // Setting Moz API connection
        $accessID = "mozscape-####"; // * Add unique Access ID
        $secretKey = "####"; // * Add unique Secret Key
        $expires = time() + 300;
        $SignInStr = $accessID. "\n" .$expires;
        $binarySignature = hash_hmac('sha1', $SignInStr, $secretKey, true);
        $SafeSignature = urlencode(base64_encode($binarySignature));
        // Connecting to Moz API url
        $reqUrl = "http://lsapi.seomoz.com/linkscape/url-metrics/".urlencode($domain)."?Cols=103079215108&AccessID=".$accessID."&Expires=".$expires."&Signature=".$SafeSignature;
        // Send request with curl
        $opts = array(
            CURLOPT_RETURNTRANSFER => true
        );
        $curlhandle = curl_init($reqUrl);
        curl_setopt_array($curlhandle, $opts);
        $content = curl_exec($curlhandle);
        curl_close($curlhandle);

        // Getting 'pda' from Moz API and then rounding
        $resObj = json_decode($content);
        $seo_grade = $resObj->pda;
        $seo_grade = round($seo_grade, 0);

        set_transient( $cache_key, $seo_grade, (60*60*72) );
    }

    return $seo_grade;
}

add_shortcode( 'moz_score','moz_score_shortcode' );

The second code is

function moz_pa_shortcode($atts) {
    extract(
        shortcode_atts(
            array(
                'domain' => get_the_title(),
            ),
            $atts
        )
    );

    if ( ! $domain )
        return; // No domain, nothing to return

    $cache_key_pa = 'agency_moz_pa_' . $domain;

    if ( false === $seop_grade = get_transient( $cache_key_pa ) ) {
        // Setting Moz API connection
        $accessID = "mozscape-#####"; // * Add unique Access ID
        $secretKey = "######"; // * Add unique Secret Key
        $expires = time() + 300;
        $SignInStr = $accessID. "\n" .$expires;
        $binarySignature = hash_hmac('sha1', $SignInStr, $secretKey, true);
        $SafeSignature = urlencode(base64_encode($binarySignature));
        // Connecting to Moz API url
        $reqUrl = "http://lsapi.seomoz.com/linkscape/url-metrics/".urlencode($domain)."?Cols=103079215140&AccessID=".$accessID."&Expires=".$expires."&Signature=".$SafeSignature;
        // Send request with curl
        $opts = array(
            CURLOPT_RETURNTRANSFER => true
        );
        $curlhandle = curl_init($reqUrl);
        curl_setopt_array($curlhandle, $opts);
        $content = curl_exec($curlhandle);
        curl_close($curlhandle);

        // Getting 'pda' from Moz API and then rounding
        $resObj = json_decode($content);
        $seop_grade = $resObj->upa;
        $seop_grade = round($seop_grade, 0);

        set_transient( $cache_key_pa, $seop_grade, (60*60*72) );
    }

    return $seop_grade;
}

add_shortcode( 'moz_pa','moz_pa_shortcode' );
14
  • Are you sure the 0s aren't coming from your API? round(null, 0) will give you 0.
    – Rup
    Commented May 15, 2020 at 11:37
  • If you want to merge this code (and I'm not sure the requests are completely the same? Your Cols parameters are different, but I don't know the API to know if that's significant) then you could e.g. save the result of the API call as a transient and have both functions read that and parse out the value, or you could e.g. have both requests write both transients (commonising the request code).
    – Rup
    Commented May 15, 2020 at 11:39
  • I'm also not sure why you want to show an SEO evaluation on the pages themselves? Is that what you're trying to do? Why would you want to show that to the web site user?
    – Rup
    Commented May 15, 2020 at 11:41
  • Actually, it's not for showing on each page but a CPT with title value as a URL will be shown.
    – Ali
    Commented May 15, 2020 at 11:49
  • @Rup, Yes because if a delete a transient, it will be updated with the correct value. For example if 10 website stats are fetched only 2-3 are 0 and when I refetch them they are correct.
    – Ali
    Commented May 15, 2020 at 11:51

1 Answer 1

0

As discussed in the comments, here's an attempt to fetch both pda and upa in a single request:

/**
 * Make a Moz v1 URL Metrics request for a given domain
 *
 * @see https://moz.com/help/links-api/v1-archive/v1-url-metrics
 * @see https://moz.com/help/links-api/v1-archive/response-fields
 * @param $domain
 */
function moz_v1_links_api_request($domain) {
    if ( !$domain ) {
        return NULL;
    }

    $cache_key = 'agency_moz_url_metrics_' . $domain;
    $url_metrics = get_transient( $cache_key );

    if ( false === $url_metrics ) {
        // Setting Moz API connection
        $accessID = "mozscape-####"; // * Add unique Access ID
        $secretKey = "####"; // * Add unique Secret Key
        $expires = time() + 300;
        $SignInStr = $accessID. "\n" .$expires;
        $binarySignature = hash_hmac('sha1', $SignInStr, $secretKey, true);
        $SafeSignature = urlencode(base64_encode($binarySignature));
        // Connecting to Moz API url
        // 103079215140 = 0x1800000024, the flags for pda, upa, ueid and uu respectively
        $reqUrl = "http://lsapi.seomoz.com/linkscape/url-metrics/".urlencode($domain)."?Cols=103079215140&AccessID=".$accessID."&Expires=".$expires."&Signature=".$SafeSignature;

        // Send request with curl
        $opts = array(
            CURLOPT_RETURNTRANSFER => true
        );
        $curlhandle = curl_init($reqUrl);
        curl_setopt_array($curlhandle, $opts);
        $content = curl_exec($curlhandle);
        $status_code = curl_getinfo($curlhandle, CURLINFO_HTTP_CODE);
        curl_close($curlhandle);

        if ( $status_code < 200 || $status_code >= 300 ) {
            // HTTP request failed
            error_log('moz_v1_links_api_request for ' . $domain . ' failed: ' . $status_code . ' ' . print_r( $content, true) );

            // Cache an empty object for 30 seconds so we retry shortly
            $url_metrics = new stdClass();
            set_transient( $cache_key, $url_metrics, 30 );
        } else {
            // Cache the object returned for three days
            $url_metrics = json_decode($content);
            set_transient( $cache_key, $url_metrics, (60*60*72) );
        }
    }

    return $url_metrics;
}

function moz_score_shortcode($atts) {
    extract(
        shortcode_atts(
            array(
                'domain' => get_the_title(),
            ),
            $atts
        )
    );

    if ( ! $domain )
        return NULL; // No domain, nothing to return

    $url_metrics = moz_v1_links_api_request( $domain );

    // Getting 'pda' from Moz API and then rounding
    if ( isset( $url_metrics->pda ) ) {
        $seo_grade = $url_metrics->pda;
        if (is_numeric($seo_grade)) {
            $seo_grade = round($seo_grade, 0);
        }
    } else {
        // No value returned
        $seo_grade = NULL;
    }

    return $seo_grade;
}

add_shortcode( 'moz_score','moz_score_shortcode' );

function moz_pa_shortcode($atts) {
    extract(
        shortcode_atts(
            array(
                'domain' => get_the_title(),
            ),
            $atts
        )
    );

    if ( ! $domain )
        return NULL; // No domain, nothing to return

    $url_metrics = moz_v1_links_api_request( $domain );

    // Getting 'upa' from Moz API and then rounding
    if ( isset( $url_metrics->upa ) ) {
        $seop_grade = $url_metrics->upa;
        if ( is_numeric( $seop_grade ) ) {
            $seop_grade = round($seop_grade, 0);
        }
    } else {
        // No value returned
        $seop_grade = NULL;
    }

    return $seop_grade;
}

add_shortcode( 'moz_pa','moz_pa_shortcode' );

or a gist here. Note that:

  • I've copied your curl code since I assume it's working fine, but there's also wp_request_get you could use instead
  • I'm now testing the HTTP status code returned by curl and logging an error
  • I'm also checking that the upa or pda value you've extracted is numeric before trying to round it, which I think is where you're going wrong: I'd guess you're getting null values here rounded to 0 because you're not noticing you're getting errors from the API
  • the API you're calling is out of date and there's a new API you should be using instead
  • this version of the API also supports batched requests which you could use instead for all of your domains at once, rather than fetching them one at a time like this.
1
  • Super, Rup, It worked like a charm. The answer is very detailed and solved the issue.
    – Ali
    Commented May 18, 2020 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.