• Feed RSS

Using the Envato API with WordPress

"Today we are going to discuss how to use the Envato API in WordPress and create a WordPress shortcode that promotes our Envato Marketplace Items inside our WordPress site. We will combine the powerful Envato API, WordPress’ flexibility and a little bit of creativity, to build an amazing plugin for our site.


Let’s Set Our Goal

In this tutorial we are going to focus on:
  • Some basic knowledge about the Envato API
  • How to use API result data inside WordPress
  • Build a WordPress Shortcode that promotes Envato Marketplace items in our WordPress site.
So let’s get into the first one!

Step 1: Understanding the Envato API

Envato provides an API that allows developers to get some information about Envato Marketplace items, users info, popular projects and so on. All possible queries are listed in the official documentation. In this article we discuss the public API only.
The Envato Public API has the following structure.
http://marketplace.envato.com/api/edge/set.json
The word set must to be replaced with an option listed in the set column of the API documentation. So if we want all information about a marketplace item we have to replace set with item:the_item_id. The final request URL will be:
http://marketplace.envato.com/api/edge/item:1263846.json
You can try to insert the URL above in your web browser and see the returned data.
We can also concatenate more than one set option in a single request to get more data. For example we want the item data and its author information. So the previous URL will become:
http://marketplace.envato.com/api/edge/item:1263846+user:evoG.json
The Envato API returns JSON, so in the next paragraph we are going to show how to manage it in WordPress.

Step 2: How to Use API Results in WordPress

In this tutorial we are not going to discuss how to create a WordPress plugin, but we are going to focus on some techniques to use the API in WordPress:
  • Send the API request
  • Manage the result data (the JSON string)
The function below fetches the data from the Envato server and returns a PHP array that contains all the informations we want.
/**
* @param String $item_id - The ID of an Envato Marketplace item
* @returns Array - The item informations
*/
function WPTP_get_item_info( $item_id ) {

 /* Set the API URL, %s will be replaced with the item ID  */
 $api_url = "http://marketplace.envato.com/api/edge/item:%s.json";

 /* Fetch data using the WordPress function wp_remote_get() */
 $response = wp_remote_get( sprintf( $api_url, $item_id ) );

 /* Check for errors, if there are some errors return false */
 if ( is_wp_error( $response ) or ( wp_remote_retrieve_response_code( $response ) != 200 ) ) {
  return false;
 }

 /* Transform the JSON string into a PHP array */
 $item_data = json_decode( wp_remote_retrieve_body( $response ), true );

 /* Check for incorrect data */
 if ( !is_array( $item_data ) ) {
  return false;
 }

 /* Return item info array */
 return $item_data;

}
We can improve the function above. To prevent stress on the Envato API server we can cache item data and request the info again after a timeout. WordPress offers us some functions to implement this feature. Let’s add it.
/**
* @param String $item_id - The ID of an Envato Marketplace item
* @returns Array - The item informations
*/
function WPTP_get_item_info( $item_id ) {

 /* Data cache timeout in seconds - It send a new request each hour instead of each page refresh */
 $CACHE_EXPIRATION = 3600;

 /* Set the transient ID for caching */
 $transient_id = 'WPTP_envato_item_data';

 /* Get the cached data */
 $cached_item = get_transient( $transient_id );

 /* Check if the function has to send a new API request */
 if ( !$cached_item || ( $cached_item->item_id != $item_id ) ) {

  /* Set the API URL, %s will be replaced with the item ID  */
  $api_url = "http://marketplace.envato.com/api/edge/item:%s.json";

  /* Fetch data using the WordPress function wp_remote_get() */
  $response = wp_remote_get( sprintf( $api_url, $item_id ) );

  /* Check for errors, if there are some errors return false */
  if ( is_wp_error( $response ) or ( wp_remote_retrieve_response_code( $response ) != 200 ) ) {
   return false;
  }

  /* Transform the JSON string into a PHP array */
  $item_data = json_decode( wp_remote_retrieve_body( $response ), true );

  /* Check for incorrect data */
  if ( !is_array( $item_data ) ) {
   return false;
  }

  /* Prepare data for caching */
  $data_to_cache = new stdClass();
  $data_to_cache->item_id = $item_id;
  $data_to_cache->item_info = $item_data;

  /* Set the transient - cache item data*/
  set_transient( $transient_id, $data_to_cache, $CACHE_EXPIRATION );

  /* Return item info array */
  return $item_data;

 }

 /* If the item is already cached return the cached info */
 return $cached_item->item_info;

}
Now the core function of our WordPress plugin is ready. We have used some WordPress functions that help us to save time. All information about them is explained in the official WordPress Codex.

Step 3: Build WordPress Shortcode

In the next steps we are going to code a useful WordPress plugin that allows us to display some informations about an Envato Marketplace item. All code below is well commented so you can easily understand each line. For more details about Writing a WordPress Plugin and the WordPress Shortcode API check out the online documentation in the WordPress Codex.

Let’s start

Let’s write the header informations for our plugin
<?php
/*
Plugin Name: WordPress Tutsplus Envato Item Info
Plugin URI: http://wp.tutsplus.com
Description: Display some informations about Envato Marketplace items
Version: 1.0
Author: Michele Ivani
Author URI: http://evographics.net
*/

Add the WordPress shortcode

Now we write the code to add the shortcode and its functionalities.
<?php
/**
* Add the shortcode using the WordPress function add_shortcode()
* We used as shortcode tag "wptp-envato-item"
*/
add_shortcode( 'wptp-envato-item', 'WPTP_add_shortcode' );

/**
* Hook to run when the shortcode is found
* @param Array $atts - shortcode attributes
* @param String $content - shortcode content (not necessary for our plugin)
* @return String - plugin HTML code
*/
function WPTP_add_shortcode( $atts, $content = null ) {

 /* Default shortcode attributes  */
 $atts = shortcode_atts( array(
  'item_id' => ''
 ), $atts );

 extract( $atts );

 /* Validation */
 if ( empty( $item_id ) ) {
  return "<p>Please insert an Envato Marketplace Item ID.</p>";
 }

 /* Get data from the API*/
 $item = WPTP_get_item_info( $item_id );

 /* Validation - Check if something went wrong */
 if ( $item === false ) {
  return "<p>Oops… Something went wrong. Please check out the item ID and try again.</p>";
 }

 /* Format the $item array */
 $item = $item['item'];
 extract( $item );

 /* Prepare the Plugin HTML */
 $html = '';

 $html .= '
 <div class="wptp_envato_item">

  <div class="wptp_title">'.$item.'</div>

  <div class="wptp_wrap">

   <div class="wptp_top">

    <div class="wptp_rating">

     <span class="wptp_desc">rating</span>'.

     WPTP_get_stars($rating)

    .'</div> <!-- end wptp_rating -->

   </div> <!-- end wptp_top -->

   <div class="wptp_middle">

    <div class="wptp_sales">

     <span class="wptp_img_sales"></span>

     <div class="wptp_text">

      <span class="wptp_num">'.$sales.'</span>
      <span class="wptp_desc">sales</span>

     </div> <!-- end  wptp_text -->

    </div> <!-- end wptp_sales -->

    <div class="wptp_thumb">
     <img src="'.$thumbnail.'" alt="'.$item.'" width="80" height="80"/>
    </div> <!-- end wptp_thumb -->

    <div class="wptp_price">

     <span class="wptp_img_price"></span>

     <div class="wptp_text">

      <span class="wptp_num"><span>${body}lt;/span>'.round($cost).'</span>
      <span class="wptp_desc">only</span>

     </div> <!-- end wptp_text -->

    </div> <!-- end wptp_price -->

   </div> <!-- end wptp_middle -->

   <div class="wptp_bottom">

    <a href="'.$url.'" target="_blank"></a>

   </div> <!-- end wptp_bottom -->

  </div> <!-- end wptp_wrap -->

 </div> <!-- end wptp_envato_item -->'; 

 return $html;
}

Star ratings function

The WPTP_add_shortcode() function above has the WPTP_get_stars() procedure that coverts the rating number to HTML stars. Let’s implement it.
<?php
/**
* Convert the rating number to HTML stars
* @param String $rating - Envato Item rating
*/
function WPTP_get_stars( $rating ) {

 /* If item rating is null the function prints a message */
 if ( ( int ) $rating == 0 ) {
  return '<div class="wptp_not_rating">Not rate yet</div>';
 }

 /* Else if rating is >= 1 the function converts it to HTML stars and returns them as a string */
 $return = '<ul class="wptp_stars">';
 $i=1;
 while ( ( --$rating ) >= 0 ) {
  $return .= '<li class="wptp_full_star"></li>';
  $i++;
 }

 if ( $rating == -0.5 ) {
  $return .= '<li class="wptp_full_star"></li>';
  $i++;
 }

 while ( $i <= 5 ) {
  $return .= '<li class="wptp_empty_star"></li>';
  $i++;
 }

 $return .= '</ul>';

 return $return;

}

Include CSS

When the shortcode functions are completed, we have to include the style.css file that styles our plugin.
<?php
/**
* Add the CSS style file
*/
add_action( 'wp_print_styles', 'WPTP_add_css' );

/**
* Attach the plugin CSS file to the WordPress site
*/
function WPTP_add_css() {
 /* Register style */
 wp_register_style( 'WPTP_css', plugins_url( 'style.css', __FILE__ ) );

 /* Enqueue style */
 wp_enqueue_style( 'WPTP_css' );
}

Step 4: Write CSS Rules

The style.css file is inside the same directory as the main plugin file and it contains all the CSS rules.
/* WordPress Tutsplus Envato Item Info - CSS Rules*/

/* Main layout and typography */
.wptp_envato_item {
 font-family: "Helvetiva Neue", Arial, sans-serif;
 margin: 20px 0;
}

.wptp_wrap { width: 210px; }

.wptp_text { display: block; }

.wptp_num {
 display: block;
 font-size: 24px;
 font-weight: 300;
 margin: 0;
 padding: 0;
 line-height: 24px;
 color: #66696d;
}

.wptp_num span {
 font-size: 14px;
 vertical-align: super;
}

.wptp_desc {
 display: block;
 font-size: 12px;
 font-weight: 300;
 margin: 0;
 padding: 0;
 line-height: 12px;
 color: #96999d;
}

.wptp_not_rating {
 color: #66696d;
 font-size: 13px;
 font-weight: bold;
}

.wptp_title { font-size: 14px; font-weight: 300; color: #66696d; margin-bottom: 10px; }

/* Stars rating section */

.wptp_rating {
 width: 82px;
 text-align: center;
 margin: 0 auto 10px auto;
}

.wptp_stars {
 margin: 0;
 padding: 0;
 list-style: none;
}

.wptp_stars li {
 margin-left: 2px;
 display: inline-block;
 vertical-align: middle;
 width: 13px;
 height: 13px;
}

.wptp_stars li.wptp_full_star { background: url(icons-sprite.png) 0px -64px ; }

.wptp_stars li.wptp_empty_star { background: url(icons-sprite.png) -14px -64px ; }

/* Sales and Price sections */
.wptp_sales, .wptp_thumb, .wptp_price {
 display: inline-block;
 vertical-align: middle;
}

.wptp_sales {
 text-align: right;
 margin-right: 10px;
}

.wptp_sales .wptp_text {
 width: 52px;
}

.wptp_img_sales {
 background: url(icons-sprite.png) 0px 0px;
 width: 32px;
 height: 32px;
 display: block;
 margin: 0 0 12px 20px;
}

.wptp_img_price {
 background: url(icons-sprite.png) 0px -32px ;
 width: 32px;
 height: 32px;
 display: block;
 margin-bottom: 7px;
}

.wptp_price {
 text-align: left;
 margin-left: 10px;
}

.wptp_price .wptp_text { width: 34px; }

/* Purchase button section */
.wptp_bottom a {
 display: block;
 width: 78px;
 height: 33px;
 background: url(icons-sprite.png) -32px 0px;
 margin: 10px auto 0 auto;
}

Conclusion

That’s it, now we can upload the plugin to our Worpdress site and use the power of WordPress shortcodes to display some info about Envato Marketplace items. For more details about Writing a WordPress Plugin and the WordPress Shortcode API check out the online documentation on the WordPress Codex.
I’m Michele Ivani and I hope this tutorial was helpful for your WordPress development. Thanks so much for reading."