Blog posts under the API tag https://webdevstudios.com/tags/api/ WordPress Design and Development Agency Mon, 15 Apr 2024 16:08:21 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://webdevstudios.com/wp-content/uploads/2022/07/cropped-wds-icon.white-on-dark-60x60.png Blog posts under the API tag https://webdevstudios.com/tags/api/ 32 32 58379230 How Thinking About Accessibility Can Lead to Success https://webdevstudios.com/2017/07/05/how-thinking-about-accessibility-can-lead-to-success/ https://webdevstudios.com/2017/07/05/how-thinking-about-accessibility-can-lead-to-success/#respond Wed, 05 Jul 2017 16:00:26 +0000 https://webdevstudios.com/?p=17164 Just over two years ago, I wrote a blog post about accessibility basics, where I introduced readers to accessibility APIs from a 30,000 foot view. Near the end, I proclaimed that WebDevStudios is “committed to building accessible websites.” Internally, an effort to make our starter theme, wd_s, pass both Section 508 and WCAG 2.0AA standards began. Since then, Read More How Thinking About Accessibility Can Lead to Success

The post How Thinking About Accessibility Can Lead to Success appeared first on WebDevStudios.

]]>
Just over two years ago, I wrote a blog post about accessibility basics, where I introduced readers to accessibility APIs from a 30,000 foot view. Near the end, I proclaimed that WebDevStudios is “committed to building accessible websites.” Internally, an effort to make our starter theme, wd_s, pass both Section 508 and WCAG 2.0AA standards began.

Since then, WebDevStudios has kept that promise. When we ship a website to a client, it passes all sorts of accessibility tests, as well as HTML and CSS validation. When a potential client asks us to provide examples of accessible websites that we have built, it’s easy to oblige. More often than not, that leads to a sale.

While impressing clients and acquiring a new project are good reasons to build an accessible website, the reality is that over 285 million people worldwide have visual impairments… which is almost the population of the United States! Thinking about accessibility is just the right thing to do.

Four Basic Principles

Make no mistake, accessibility is hard. So where should you start? To keep from getting overwhelmed, take a cue from Foundation by Zurb and follow four basic principles:

1) Structure your document properly

Modern web browsers can do a lot of the heavy lifting… if you write semantic HTML.

  1. Use <button> instead of making <a>, <div> and <spans> look like buttons.
  2. Use headings <h1><h6> to help provide both structure and context to screen readers.
  3. Steer clear of “enhanced” form field plugins. Ask yourself, “Is it really worth having a pretty dropdown, when it is completely unusable by 285 million people?”
  4. Use WAI-ARIA to help provide additional semantics to describe role, state, and properties.
  5. Read more about “How Writing Semantic HTML Can Help Accessibility” by Jeffrey de Wit.

2) <label> everything

For 285 million people, a screen reader is the only way to “view” a website. When it’s read back to them… does your website makes sense?

  1. Make sure form fields have a <label>. It is OK to hide labels with CSS: <label class="sr-only">
  2. Using <fieldset> and <legend> to group related form elements.
  3. Provide descriptive alt attributes on images: <img alt="A hen Mallard landing on a pond"> vs <img alt="mallard_duck-1.jpg">
  4. Read more about “Labeling Controls” from w3.org.

3) Don’t rely on purely visual cues

If a page is being read to a user by a screen reader, it may not be obvious what the user is supposed to do next.

  1. Make sure call to actions have labels that can be read by a screen reader.
  2. Do call to actions meet a minimum contrast ratio? Meaning, can this person actually see/read it? Make sure the contrast ratio (on everything from text to buttons) is at least 1:4.5 for normal text and 3:1 for headings.

4) Make everything usable on a keyboard, mouse, and touch screen

  1. Make sure you can use the tab, spacebar, and arrow keys to navigate a web page.
  2. Give users the option to skip around a page.
  3. Complex components such as sliders or modals should be tested with arrow and esc keys.

Tools Can Help

These accessibility testing tools can help, by pointing out areas of your web page that need work.

  • Tenon.io – Will check your website against Section 508 and WCAG 2.0, and provide recommended fixes.
  • WAVE – Similarly, WAVE can test your website against accessibility standards and even display contrast issues.
  • Total Validator – Available for Windows and MacOS, this tool can test entire websites against a wide range of validation tests.

Conclusion

By thinking about and ultimately acting on these principles during the entire life cycle of a project, from scoping to design, development, and QA, not only will you be making your website usable by those with disabilities, you will be doing the right thing. This will come with many other benefits including: long-term maintainable code, SEO juice, and that feeling deep down when you do something nice for someone else. In my book, it doesn’t get more successful than that.

Further Reading

The post How Thinking About Accessibility Can Lead to Success appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2017/07/05/how-thinking-about-accessibility-can-lead-to-success/feed/ 0 17164
WP-API: Endpoint Namespaces https://webdevstudios.com/2015/12/22/wp-api-endpoint-namespaces/ https://webdevstudios.com/2015/12/22/wp-api-endpoint-namespaces/#comments Tue, 22 Dec 2015 18:52:58 +0000 http://webdevstudios.com/?p=12042 WordPress is getting a JSON Rest API added to core. The first part of the API is actually already included. The endpoint infrastructure is in 4.4. As developers build extensions to the API, we need to take responsibility for our actions and how they can affect a site. WordPress is unique in that it is the ultimate generic API tool and anything can Read More WP-API: Endpoint Namespaces

The post WP-API: Endpoint Namespaces appeared first on WebDevStudios.

]]>
WordPress is getting a JSON Rest API added to core. The first part of the API is actually already included. The endpoint infrastructure is in 4.4. As developers build extensions to the API, we need to take responsibility for our actions and how they can affect a site. WordPress is unique in that it is the ultimate generic API tool and anything can be created utilizing this new tool.

“The infrastructure of the API itself, supports basically anything you can throw at it. If you take away the core endpoints, it is essentially a framework for building APIs, and you can build those however you like.” – Ryan McCue

Namespaces

To avoid collisions, namespaces are something to be thoughtful about. Namespaces are the slugs in the URL before the endpoint. Also, the schema and structure of your data should be a consideration. The core endpoint namespace is:

/wp/

This means it is reserved for core endpoints. Similarly, you may come across plugins that have a namespace. You should probably not add endpoints to a previously used namespace unless the data is specific to that plugin. Think of namespaces like you would with class or function names; they need to be unique. If you are creating endpoints, then add filters in your JSON response code so others can add more data to your existing namespaces endpoints.

What happens when you try and register a namespace and endpoint that already exists? Nothing–it actually gets ignored if the code is loaded after the previous registration. If you register a namespace and a plugin loads before your plugin, then they win and your endpoint will get ignored. To avoid this, create unique namespaces (PLEASE).

If it’s a plugin hosted in the WordPress repo, the slug of the plugin is good namespace for your endpoints. The slug is in the URL after /plugins/. These are unique to each hosted plugin. (This may not be the case for some plugins; they may choose a unique name based on other factors. For example, the core namespace is ‘wp.’)

Options are everything here. You can create wildly different APIs for a myriad of applications. This is one of the reasons I feel WordPress’ Rest API is going to be the go-to framework for creating APIs. You have authentication and administration tools baked in along with Custom Post Types, Taxonomies, and Meta, OH MY! Though, we have almost infinite API possibilities with data structure I think it is good to have some standardized endpoint structures.

Taking core namespaces and endpoints as a basis for creating your own endpoints is the best method. Accessing your custom endpoints will feel natural to a user if they are similar. Looking at the core endpoint for posts:

/wp-json/wp/v1/posts

You may think to create a custom endpoint for a Custom Post Type you might use:

/wp-json/wp/v1/custom-post-type

You could also register your own namespace using the CPT slug:

/wp-json/custom-post-type/v1/posts

The lesson here is you need to decide what is best for your data. If you are adding a simple CPT, you can access the data using the ‘?type=’ parameter when visiting the posts endpoint but if you have complex data structures and a lot of extra meta you may want to go the route of creating unique endpoints. If your plugin will have lots of endpoints, utilizing a custom namespace is the way to go. Note that Custom Post Types will not show unless it has the argument ‘show_in_rest’ during the creation of the type.

JSON Structure

You can hook into the filter ‘rest_prepare_post’. This is the filter you would use to add post meta or any other data to the posts endpoint. Create your own unique filter names, like ‘rest_prepare_my_custom_post_type.’

The filter mentioned above, ‘rest_prepare_post,’ can add or remove anything from a post response. If a plugin filtered the API response and added a new key to the data array, then you came along and added the same key, it would bump their data out of the API response and you may break their site or application. You can add any data in any structured way to the API. This is its greatest power, but it can get wild if there is not some sort of standardized structure. If you have five plugins adding the same meta to five different parent keys it could get messy! Plus, how would a client accessing your API know where the meta for the post is stored?

Conclusion

There is no set method structuring APIs and can’t truly be enforced. Maybe the API needs some guidelines on where to place extra data in the structure. Until then it is best to create our own namespaces / endpoints specific to your data’s needs. If you need to learn how to add the endpoints, hit up the WP-API docs site.

*original image by Nimish Gogri

The post WP-API: Endpoint Namespaces appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2015/12/22/wp-api-endpoint-namespaces/feed/ 3 12042
How To Create an Auto-Updating Widget Using WP-API https://webdevstudios.com/2015/03/26/how-to-create-an-auto-updating-widget-using-wp-api/ https://webdevstudios.com/2015/03/26/how-to-create-an-auto-updating-widget-using-wp-api/#comments Thu, 26 Mar 2015 17:30:17 +0000 http://webdevstudios.com/?p=10892 In my last post, I gave you an overview of WP-API. Read through that post if you need a primer on the capabilities of WP-API. For this post, I will offer an example of API usage and how it can benefit site owners by creating more dynamic content. In this post, we will go over Read More How To Create an Auto-Updating Widget Using WP-API

The post How To Create an Auto-Updating Widget Using WP-API appeared first on WebDevStudios.

]]>
In my last post, I gave you an overview of WP-API. Read through that post if you need a primer on the capabilities of WP-API. For this post, I will offer an example of API usage and how it can benefit site owners by creating more dynamic content.

In this post, we will go over creating a comment widget that auto-updates via WP-API without refreshing the page, and how to use AJAX to poll the API for new comments and then display those comments in a sidebar widget.

Here’s a gif of the widget in action as it would look in the Twenty Twelve theme:

TestyAntiqueHoatzin

The first thing you will need is to install the WP-API plugin. WordPress has not included this in core yet as it is still in active development. (Make sure it is the correct plugin by Ryan McCue!)

Activate the WP-API plugin. There are no settings for this plugin. Visit your site’s API URL (yoursite.com/wp-json) to verify the API is active and working. If you want to learn more about the API, visit the previous post in this series or peruse the WP-API getting started guide.

After you have verified the API is working and returning JSON data, you can install the example project plugin outlined in this post. This is a fully working plugin. You can look through the plugin code base to understand how it works or read the rest of the post that highlights how this plugin was created so you can learn how to create your own dynamic content using the WP-API.

WHY JSON?

Normally, when you load a WordPress page, the dynamic content is compiled on the server and then displayed. In laymen’s terms, PHP is like a bunch of ingredients and the server mixes it together to give you something to consume. The PHP in WordPress templates produces dynamic content that can supply posts, pages, media, comments, or some other content type.

PHP processes before the page load, so there is a possibility that it could slow down the page load. Anything that helps a website’s time to first render is a good thing. We all hate when the page loads are slow. Search engines (hi Google, how ya doin’?) are even against slow loading sites. Page caching helps with page load but also, is the opposite of what we want to achieve–which is is live updated content.

Using JSON to display dynamic content instead of replying on the server to process the PHP frees up the page loading. You might not necessarily see the dynamic content any faster, but the time to display non-dynamic parts of a page can load faster with a perceived snappier user experience. Lazy loaded images are an example of not loading content at first to allow faster page rendering.

If your content is updated frequently, using JSON to display dynamically loaded content on the page will work well for you. You may want a user to get the most timely content as possible without requiring a full page refresh; this is where a JSON API comes in handy. Pinging a JSON API for data is the simplest method possible.

THE CODE

We are not going to go over the code line by line, but I will highlight the parts that are important. The example plugin uses a Widget Boilerplate maintained by WebDevStudios.

The current WP-API plugin does not contain a comments endpoint to access all comments, but it’s in development for version 2.0. No problemo–the API allows custom endpoint creation and we can supply any data your WordPress lovin’ heart desires.

To add endpoints to the API, we can add a filter to ‘json_endpoints’, passing an array with information on how the endpoint should be structured. In the routes function, we tell it what function to run when we are at the endpoint on the site. Visit url/wp-json/comments and the get_items() function runs. Though we have used “comments” as the endpoint, this may cause a collision if another plugin or even the WP-API itself registered the same endpoint. If you create your own endpoints make sure they are unique. You can find the following three functions in file comments-api-endpoints.php.

– Register endpoint

function wds_api_comments_init() {
    $wds_api_comments = new WDS_API_COMMENTS();
    add_filter( 'json_endpoints', array( $wds_api_comments, 'register_routes' ) );
}
add_action( 'wp_json_server_before_serve', 'wds_api_comments_init' );

– Register route

function register_routes( $routes ) {
    $routes['/comments'] = array(
array( array( $this, 'get_items'), WP_JSON_Server::READABLE ),
);
    return $routes;
}

After a route is registered, we need to return a JSON array of data. Since we are getting the last few comments, WordPress has the function get_comments(). Pass in a few parameters and then convert the results into JSON. The endpoint data functions can be as complex as needed to return any type of data in your database. This function is lacking a bit of error handling if no comments exists. We could return a message if there are no comments.

– Get comments

function get_items() {
    $comments = get_comments( apply_filters( 'widget_comments_args', array(
'number' => 5,
'status' => 'approve',
'post_status' => 'publish'
) ) );

    return wp_send_json( $comments );
}

Now that we have an endpoint with data, we use AJAX to get the comments and display them in our widget. First thing is to enqueue our JavaScript file that has our AJAX for pinging the API for comment data. We have a check to see if the widget is active and we are on the front of the site. We don’t want to ping the API unnecessarily. Also, we need to add the API URL to the header as a script variable to be used by jQuery AJAX.

– Enqueue scripts

function scripts() {
    
    $jsfile = WDS_COMMENT_WIDGET_PLUGIN_URL . 'inc/comment-widget.js';
        
    if ( is_active_widget( false, false, $this->widget_slug, true ) && ! is_admin()  ) {
        wp_enqueue_script( 'script-name', $jsfile, array(), WDS_COMMENT_WIDGET_VERSION, true );
      }
}

We will also need to add an API variable; we can retrieve it later in our AJAX. We hook this to wp_head so its ready when the page loads.

– API url

function apiurl() {
    ?>
    <script type="text/javascript">
    var apiurl = '<?php echo trailingslashit( site_url('wp-json') ) ?>';
    </script>
    <?php
}

Now let’s take a look at that JavaScript file we enqueued. It contains jQuery $.ajax to ping our endpoint, get comment data, and process it. We have an on success function to process the data into HTML and add it to our widget. You might see a set interval–this is to set a specific amount of time to run our AJAX. We run the AJAX on page load then set an interval, after two minutes kill set interval so the API isn’t pinged constantly. This is a simple method. Another (possibly better) way might be to detect mouse moves (scrolling or click event) to see if a user is still active before killing the set interval. You could also use the heartbeat API to run our AJAX in intervals.

– AJAX

(function($) {

    // run get comment function and poll api for comments
    get_comments();

    // set interval to check every 15 seconds
    var refresh = setInterval( function() {
        get_comments();
    }, 15000);


    // after 2 mins kill api check
    setTimeout( function() {
        clearInterval(refresh);
    }, 120000);


    /**
     * get_comments function.
     * 
     */
    function get_comments() {
    
        // borrow the admin loading spinner
        $('#wds-comment-widget').html( '<img src="/wp-admin/images/wpspin_light.gif">' );
    
        $.ajax({
            url: apiurl + 'comments',
            dataType: 'json',
            type: 'GET',
            success: function(data) {
                // send data to processing function
                process_comment_data( data );
            },
            error: function() {
               console.log('Error with API');
               $('#wds-comment-widget').html( 'No comments' );
            }
        });
        
    }



    /**
     * process_comment_data function.
     * 
     */
    function process_comment_data( data ) {
        
        // start an array for comments
        var comments = [];
        
        $.each( data, function( index, value ){
        
            comments += '<li postid="' + data[index]['ID'] + '">' + data[index]['comment_author'] + ' on <a href="' + data[index]['guid'] + '">' + data[index]['post_title'] + '</a></li>';
        
        });
        
        setTimeout( function() {
            $('#wds-comment-widget').html( '<ul>' + comments + '<ul>' );
        }, 500);
        
    }
    
    
 })(jQuery);

That’s all there is to it! Check out the example plugin for the full code. Hopefully this post helps you to use WP-API on your site, and allows you to offer viewers more dynamic content!

The post How To Create an Auto-Updating Widget Using WP-API appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2015/03/26/how-to-create-an-auto-updating-widget-using-wp-api/feed/ 2 10892
An Overview of the WordPress JSON API https://webdevstudios.com/2014/10/16/an-overview-of-wordpress-json-api/ https://webdevstudios.com/2014/10/16/an-overview-of-wordpress-json-api/#comments Thu, 16 Oct 2014 18:40:51 +0000 http://webdevstudios.com/?p=8610 ** UPDATED POST FOR WP-API V2 HERE WordPress has had no formal REST API. There is the crude XMLRPC, but we won’t go into the gory details of the past. As part of Google Summer of Code (GSOC), Ryan McCue submitted a proposal for creating a formal JSON API to be included in WordPress core and Read More An Overview of the WordPress JSON API

The post An Overview of the WordPress JSON API appeared first on WebDevStudios.

]]>
** UPDATED POST FOR WP-API V2 HERE

WordPress has had no formal REST API. There is the crude XMLRPC, but we won’t go into the gory details of the past.

As part of Google Summer of Code (GSOC), Ryan McCue submitted a proposal for creating a formal JSON API to be included in WordPress core and therefore available to every WordPress.org install.

For those who may not know what a REST API is; it stands for Representational State Transfer. In short, it separates client from the server. Each request from any client contains all the information necessary to service the request, and session state is held in the client.

There is no “official” standard for RESTful web API’s. This is because REST is an architectural style. You can use HTML, XML or JSON. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write, it’s very easy for machines to parse and generate. This is largely in part the reason it has become the de facto choice when creating REST API’s, and also the reason JSON data is the response format of the forthcoming API.

JSON API OVERVIEW

Currently, you can use the WordPress JSON API on your site via a plugin you install from the WordPress repository; the functionality in this plugin will eventually be included in the core WordPress software. Activate it and you now have a REST API for your site’s content. The plugin exposes your data in JSON format in the following content types:

  • Posts
  • Pages
  • Users
  • Media
  • Taxonomies
  • Custom Post Types

The response data is like what you would get in the WordPress loop, only the format is JSON. This allows you to display it in any way you wish. You can even filter the API calls in a similar fashion to the loop.

Want to get your site’s posts? Simply send a GET request to url.com/wp-json/posts. Update user with ID 4? Send a POST request to url.com/wp-json/users/4. Get all posts with the search term “awesome”? GET url.com/wp-json/posts?filter[s]=awesome. It’s that easy.

Let’s look at some of the JSON responses from WP-API developer @RachelBaker‘s site:

This is just a small example of the wide range of data you are able to request from the API.

Some API calls require authentication, just like WordPress requires authentication to access wp-admin, or to create new posts. Most GET requests do not require authentication, this allows you to display content via the API on the front of your site, or in an external app without a user needing to log in.

Here is an example AJAX call to filter the posts API endpoint response:

$.ajax({
    url: 'http://url.com/wp-json/posts',
    data: {
        filter: {
        'posts_per_page': 5
        }
    },
    dataType: 'json',
    type: 'GET',
    success: function(data) {
        // success code
    },
    error: function() {
        // error code
    }
});

Most anything you can filter get_posts you can use to filter the posts JSON response. The other API endpoints are filtered in much the same way.

Also, you can use authenticated API calls to PUT or DELETE content. To edit a post you send a PUT request to the API at url.com/wp-json/posts/id where id is the post id you wish to edit. To add meta to a post send a Post request to url.com/wp-json/posts/id/meta and in your ajax supply a key and value in the data parameter. This really could not be any more simple.

In a lot of cases, people choose WordPress as their CMS because it’s very easy to add new content types. Another benefit of the JSON API is it works well with Custom Post Types (CPT). To access a CPT you add a type parameter to the API request (url.com/wp-json/posts?type=cpt); and you can add any other get post filters as well.

There is one gotcha with posts, and that is custom meta, it’s not added for you. If you want to include custom meta it is easy to add with a filter to json_prepare_post.

Example function to add meta to posts:

function custom_json_api_prepare_post( $post_response, $post, $context ) {

    $meta = get_post_meta( $post['ID'] );
    $post_response[‘meta_field_name’] = $meta;

    return $post_response;
}
add_filter( 'json_prepare_post', 'custom_json_api_prepare_post', 10, 3 );

There is also some great documentation for the API, read through them and even check out issues on Github to get a better handle on current state of the API.

API USAGE

You may be asking why you need a JSON API in WordPress. There are many reasons, but the main reason is to allow access to data without any constraints on its usage. This allows developers to create unique experiences, one of them being custom applications. Also, plugins and themes can access the data on your site and display the content more efficiently than reloading the entire page. Sections of a site can be updated live or with user interaction.

Maybe you have a Multisite install, and each site is a store. You may want to display all of the sales items from each site on the network that are tagged “Halloween”. The API makes these types of data mash-ups very easy to implement.

Maybe you want to post to your WordPress site from a web connected device. Smart devices are gaining momentum, apps from these devices can access your API, and your site will handle the request.

I could list a hundred more ideas for usage but the point of why we need and API in WordPress is this…

If every WordPress site is running a similar API data structure, and the sites data is open, amazing things can be created.

This post is the first in a series where I will go deeper into all aspects of the API, keep an eye out.

Some Additional Resources Worth Checking Out

http://wp-api.org
https://wordpress.org/plugins/json-rest-api
http://apppresser.com/using-wordpress-rest-api-mobile-app
http://wordpress.tv/2014/07/06/rachel-baker-put-your-content-to-rest-with-wp-api
http://wordpress.tv/2014/10/13/andrew-nacin-post-modern-wordpress

The post An Overview of the WordPress JSON API appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2014/10/16/an-overview-of-wordpress-json-api/feed/ 35 9526
Using APIs to Integrate with WordPress https://webdevstudios.com/2014/08/21/using-apis-to-integrate-with-wordpress/ https://webdevstudios.com/2014/08/21/using-apis-to-integrate-with-wordpress/#comments Thu, 21 Aug 2014 20:11:03 +0000 http://webdevstudios.com/?p=8419 Editor’s note: This blog post was updated on June 27, 2018. Instagram has deprecated much of this API. This widget still works, if you’re showing your own content. Even then, that functionality will be gone in 2020. It’s recommended you look into using the new Instagram Graph API for media consumption. What is an API? API stands for Read More Using APIs to Integrate with WordPress

The post Using APIs to Integrate with WordPress appeared first on WebDevStudios.

]]>
Editor’s note: This blog post was updated on June 27, 2018. Instagram has deprecated much of this API. This widget still works, if you’re showing your own content. Even then, that functionality will be gone in 2020. It’s recommended you look into using the new Instagram Graph API for media consumption.

What is an API? API stands for “application programming interface” but that does not help explain what an API is. The simplest way I could explain what an API is: a way to handle data somewhere other than where you are. A good example that is probably being used on many WordPress websites is a typical Twitter widget. Depending on the widget different API’s may be being used there, and it is displayed in different ways but no matter what way you do it what is happening is your website is using the Twitter API to retrieve and display tweets. However, API does not always mean connecting to an external website and getting data; you could be sending data, or you could even be working with data within your own website. The WordPress settings API is an API for managing your WordPress settings; that is when you are not using CMB!

When working with APIs in PHP you typically see cURL being used to connect to other servers to get or send data. cURL is great, except when the web server does not have cURL installed. So how do you make sure that your plugin or widget that uses APIs will work on as many of the varying server environments across the whole 30% of the internet WordPress powers? WordPress offers you a HTTP API that you can use to access other APIs! Instead of using cURL to send a GET or POST data, we use the wp_remote_get() or wp_remote_post() functions and simply pass in a URL and what data we want to send. I will be using these.

Greg Rickaby, Director of Engineering, and I put our heads together a little while back and extracted an Instagram widget we had created for a client site into its own plugin. This plugin and widget is very simple and will grow later, but it is a perfect proof of concept for accessing an API and then using that data. I will be examining how we went from our goal of using the Instagram API to create a widget that will grab the latest X shared photos, cache them, and then display them. For the purposes of this post, I am going to skip creating the widget itself, but you can check out the source code on our GitHub!

Most APIs require some form of authentication in order to use the API. The same way you need to login to your Instagram account to share your pictures, you need to login to get your data. For our purposes, we will need to create a “client” within Instagram – this is what you will authenticate to the API with. To get the credentials you will need to login to the Instagram developers console and register a client. Where it asks for your website and oAuth redirect URL you can enter your website URL in both fields (we are not dealing with oAuth today but they are required). Once registered you will be given your client ID which we will use to authenticate with the API.

Add Instagram API Client

Now that we have our keys to the Instagram API, we can start getting our data! Let’s step through the function below and examine how we can use the WordPress HTTP API to connect to Instagram, authenticate with our new client ID, and cache this response locally for a short period of time to help improve performance and reduce the number of API calls made on every page load.

To cache our data we are going to use the Transients API, and to do this we need a unique key that is no more than 45 characters in length. While this can sometimes at times be a bit difficult to have a readable AND short key I’ve found that having a readable prefix and concatenating that with an MD5 hash of some unique data will give me a unique and short key, every time. When this key is passed into get_transient() if cached data is available it will be returned, otherwise it will return false. If cached data is available skip all the processing and just return it! This will help keep your site running as quick as it can.

$key = 'wds_instagram_widget_' . md5( $this->id, $args['count'] );
if ( false === ( $instagrams = get_transient( $key ) ) ) {
// ...
}

When results are not cached yet though, we need to make that API call. To do this we build the URL that we need to access, which in this case required passing the Instagram user ID (not the username, the integer ID) along with a two query args for the client ID we create earlier and the count of how many photos we want returned. Once the URL has been created, we pass it to wp_remote_get() wrapped in the add_query_arg() function to add the data we need to pass along. Every HTTP request made is going to return a status code with its response in the header, a good quick way to make sure that you are getting the response you expect is to check this code. Typically a good response is going to return a 200, if we do not receive a 200 code (using the wp_remote_retrieve_response_code() function to check the response) from this endpoint of the Instagram API something did not go quite right and we are just going to bail out right now by returning false.

$api_url = 'https://api.instagram.com/v1/users/' . esc_html( $user_id ) . '/media/recent/';
$response = wp_remote_get( add_query_arg( array(
    'client_id' =&gt; esc_html( $client_id ),
    'count'     =&gt; absint( $count )
), $api_url ) );

// Is the API up?
if ( ! 200 == wp_remote_retrieve_response_code( $response ) ) {
    return false;
}

If you were to access that URL directly once built you would see a nice blob of machine readable JSON! That JSON may mean nothing to you but once WordPress can get it’s hands around it, json_decode() will turn that JSON into a usable PHP object, or if you pass true as the second argument, you will be returned an array. Just in case the API is acting up, or the user ID is wrong, or a client ID is wrong, or for any other reason if we are not returned an array. If the response is not an array, just like before bail out and return false.

$instagrams = json_decode( wp_remote_retrieve_body( $response ), true );

// Are the results in an array?
if ( ! is_array( $instagrams ) ) {
    return false;
}

Finally, once we have received our data and verified it is what we are expecting as well, we can we can save it to a transient using the key from before and cache so the next site visitor can get their page just a little bit faster.

set_transient( $key, $instagrams, apply_filters( 'wds_instagram_widget_cache_lifetime', 1 * HOUR_IN_SECONDS ) );

Putting it all together when we display our widget we can use this function to query the Instagram API for a users photos. Once we verify we did not return false in those few cases with a simple loop our photos are being displayed.

$instagram = $this->get_instagrams( array(
   'user_id'   => $instance['user_id'],
   'client_id' => $instance['client_id'],
   'count'     => $instance['count'],
) );

// If we have Instagrams
if ( false !== $instagram ) : ?>

   <?php
      // Allow the image resolution to be filtered to use any available image resolutions from Instagram
      // low_resolution, thumbnail, standard_resolution
      $image_res = apply_filters( 'wds_instagram_widget_image_resolution', 'standard_resolution' );

      echo $args['before_widget'];
      echo $args['before_title'] . esc_html( $title ) . $args['after_title'];
   ?>

   <ul class="instagram-widget">

   <?php
      foreach( $instagram['data'] as $key => $image ) {
         echo apply_filters( 'wds_instagram_widget_image_html', sprintf( '<li><a href="%1$s"><img class="instagram-image" src="%2$s" alt="%3$s" title="%3$s" /></a></li>',
            $image['link'],
            $image['images'][ $image_res ]['url'],
            $image['caption']['text']
         ), $image );
      }
   ?>

      <a href="https://instagram.com/<?php echo esc_html( $username ); ?>"><?php printf( __( 'Follow %1$s on Instagram', 'wds-instagram' ), esc_html( $username ) ); ?></a>
   </ul>

<?php endif;

That’s it! You have successfully integrated Instagram into WordPress using their API. Using these basic concepts you can expand to integrate just about anything you want; so long as it has an API.

The post Using APIs to Integrate with WordPress appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2014/08/21/using-apis-to-integrate-with-wordpress/feed/ 17 8804
CyberSource and 2Checkout Add-Ons for iThemes Exchange https://webdevstudios.com/2013/11/18/cybersource-and-2checkout-add-ons-for-ithemes-exchange/ https://webdevstudios.com/2013/11/18/cybersource-and-2checkout-add-ons-for-ithemes-exchange/#respond Mon, 18 Nov 2013 18:56:53 +0000 http://webdevstudios.com/?p=7913 WebDevStudios is proud to announce two more add-ons for the iThemes Exchange plugin! We now have three total add-ons for this easy to use Ecommerce option; the first being the PayPal Pro Add-On. All three of these add-ons are payment gateway options for the iThemes Exchange Plugin so customers can use their existing payment gateway Read More CyberSource and 2Checkout Add-Ons for iThemes Exchange

The post CyberSource and 2Checkout Add-Ons for iThemes Exchange appeared first on WebDevStudios.

]]>
WebDevStudios is proud to announce two more add-ons for the iThemes Exchange plugin! We now have three total add-ons for this easy to use Ecommerce option; the first being the PayPal Pro Add-On. All three of these add-ons are payment gateway options for the iThemes Exchange Plugin so customers can use their existing payment gateway with the Exchange store. The goal is make it feel seamless when going through the checkout process.

2co-cybersource

Now, to introduce our two new add-ons, CyberSource and 2Checkout. Screen-Shot-2013-11-13-at-4.42.36-PM

With the CyberSource Add-On, you have the ability to accept credit cards on your site, via the CyberSource payment gateway.

How To Use The CyberSource Add-On:

To get started, enter your Merchant ID, Live Transaction Security Key and Test Transaction Security Key on the CyberSource Add-on settings page.

Select your transaction sale method: Authorize and Capture or Authorize.

You can also enable and disable CyberSource Sandbox Mode and change the purchase button label.

The 2Checkout Add-On allows 2Checkout members to use their account to purchase items off of your site. This option is for members only. After clicking on the purchase button, the customer will be redirected to the 2Checkout payment process.

2checkout-screenshotHow To Use The 2Checkout Add-On:

To get started taking payments through 2Checkout, enter your 2Checkout SID and Secret Word on the 2Checkout Add-on settings page.

In the add-on settings you can choose Credit Card or PayPal as the default payment method.

You can also enable and disable test 2Checkout Demo mode and change the Purchase button text to whatever you prefer.

WDS is very excited about this on-going relationship with iThemes and we can’t wait to continue making Exchange awesome for users. If you want to learn more about the iThemes Exchange plugin and these add-ons, you can visit their site!

The post CyberSource and 2Checkout Add-Ons for iThemes Exchange appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2013/11/18/cybersource-and-2checkout-add-ons-for-ithemes-exchange/feed/ 0 7913
Post Google Map WordPress Plotting Plugin https://webdevstudios.com/2009/07/16/post-google-map-wordpress-plotting-plugin/ https://webdevstudios.com/2009/07/16/post-google-map-wordpress-plotting-plugin/#comments Fri, 17 Jul 2009 01:54:12 +0000 http://webdevstudios.com/?p=1889 Fresh off the dev table is our newest plugin, Post Google Map.  This plugins allows you to add addresses to posts and pages.  These addresses are then plotted on a google map in your sidebar when viewing the post or page!  It’s a great way to localize your posts, news, stories, events, etc. Hovering over Read More Post Google Map WordPress Plotting Plugin

The post Post Google Map WordPress Plotting Plugin appeared first on WebDevStudios.

]]>
Fresh off the dev table is our newest plugin, Post Google Map.  This plugins allows you to add addresses to posts and pages.  These addresses are then plotted on a google map in your sidebar when viewing the post or page!  It’s a great way to localize your posts, news, stories, events, etc.

Google Map Widget ScreenshotHovering over a plot will display the title of the post, address, and also a thumbnail from the post if any images exist. Easily add and delete a single or multiple addresses to each post.

Viewing a single post displays only addresses attached to that post/page, viewing any other page will show the most recent plots across your entire site. You can also set a custom title and description for each address saved. If no title or description is entered the post title and excerpt will be used.

Installation

  1. Upload the post-google-map folder to the plugins directory in your WordPress or WPMU installation
  2. Activate the plugin
  3. Click on “Post Google Map” under Settings. You MUST obtain a Google Maps API key for this plugin to work. http://code.google.com/apis/maps/signup.html
  4. Add the “Post Google Map” widget to your sidebar
  5. Add an address to any post/page

This plugin has been tested and works on WordPress 2.8.1 and WordPress MU (WPMU) 2.8.1.

Visit our Official Post Google Map plugin support page.

You can download the plugin at the Plugin Directory here: Post Google Map on WordPress.org

If you experience any bugs please visit our Support Forum.

post-google-map-add-address
Add an address to any post or page.

The post Post Google Map WordPress Plotting Plugin appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2009/07/16/post-google-map-wordpress-plotting-plugin/feed/ 7 1889
Facebook Applications now with Metrics! https://webdevstudios.com/2008/08/08/facebook-applications-now-with-metrics/ https://webdevstudios.com/2008/08/08/facebook-applications-now-with-metrics/#comments Sat, 09 Aug 2008 02:42:15 +0000 http://webdevstudios.com/?p=502 Facebook recently announced a new Metrics and Visualizations section for developers. Facebook Application Developers will now have access to more detailed stats about their public applications performance. This new feature will display stats on user actions including canvas page views, clicks on profile boxes, confirmation of feed forms, and the adding and removing of bookmarks. Read More Facebook Applications now with Metrics!

The post Facebook Applications now with Metrics! appeared first on WebDevStudios.

]]>
Facebook recently announced a new Metrics and Visualizations section for developers.

Facebook Application Metrics ReportFacebook Application Developers will now have access to more detailed stats about their public applications performance. This new feature will display stats on user actions including canvas page views, clicks on profile boxes, confirmation of feed forms, and the adding and removing of bookmarks.

The analytics will also help show trends in your data with a graphical report. Custom date range reports can also be viewed.

This new feature will help Facebook Application Developers to visualize application growth, gauge user response, and ultimately build a better user experience.

The post Facebook Applications now with Metrics! appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2008/08/08/facebook-applications-now-with-metrics/feed/ 1 14769
Microblogging Website Identi.ca Launches a Twitter Compatible API https://webdevstudios.com/2008/08/08/microblogging-website-identica-launches-a-twitter-compatible-api/ https://webdevstudios.com/2008/08/08/microblogging-website-identica-launches-a-twitter-compatible-api/#comments Fri, 08 Aug 2008 22:46:39 +0000 http://webdevstudios.com/?p=460 Laconica, the Open Source Microblogging Framework that runs http://Identi.ca, has released a Twitter compatible API. So what is Identi.ca? Identi.ca is an Open Network Service. Our main goal is to provide a fair and transparent service that preserves users’ autonomy. In particular, all the software used for Identi.ca is Free Software, and all the data Read More Microblogging Website Identi.ca Launches a Twitter Compatible API

The post Microblogging Website Identi.ca Launches a Twitter Compatible API appeared first on WebDevStudios.

]]>
Identi.ca LogoLaconica, the Open Source Microblogging Framework that runs http://Identi.ca, has released a Twitter compatible API.

So what is Identi.ca?

Identi.ca is an Open Network Service. Our main goal is to provide a fair and transparent service that preserves users’ autonomy. In particular, all the software used for Identi.ca is Free Software, and all the data is available under the Creative Commons Attribution 3.0 license, making it Open Data.

By creating an open Application Programming Interface (API) around the Twitter API, any application created that integrates with the Twitter API will now work seamlessly with the Indenti.ca API. This move helps solidify a standard with Twitter as the market leader.

At WebDevStudios, we are highly experienced at integrating custom software applications with any open API, such as the Identi.ca and Twitter API.

The post Microblogging Website Identi.ca Launches a Twitter Compatible API appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2008/08/08/microblogging-website-identica-launches-a-twitter-compatible-api/feed/ 2 14768