Simple WordPress HTTP API Tutorial

This article is to show beginners how to consume a Web Service and display results on your WordPress website. I say beginner, I mean a beginner in using Web Services or  a beginner in WordPress development. I also assume you have an idea of what web services are, what a Endpoint is, what is JSON, and what are RESTFUL services, You are someone just looking for advice on how to accomplish this in a WordPress website. Some knowledge of WordPress, some basic PHP and some basic knowledge of WordPress theme development and/or WordPress plugin development are suggested. If you are a brand new WordPress user that has never written any code this might not be the article for you. A person that has written some PHP code and has knowledge of the WordPress file structure should be able to understand this article.   To start, we need to take a look at the documentation for WordPress HTTP API.

WordPress HTTP API

 

The functions below are the ones you will use to retrieve an URL. Please be aware that these functions will return a WordPress WP_Error class on failure.

* wp_remote_get() – Retrieves a URL using the GET HTTP method.
* wp_remote_post() – Retrieves a URL using the POST HTTP method.
* wp_remote_head() – Retrieves a URL using the HEAD HTTP method.
* wp_remote_request() – Retrieves a URL using either the default GET or a custom HTTP method (should be caps) that you specify.

The other helper functions deal with retrieving different parts of the response and do the testing for WP_Error for you, these make usage of the API very simple and are the preferred method for processing response objects.

* wp_remote_retrieve_body() – Retrieves just the body from the response.
* wp_remote_retrieve_header() – Gives you a single HTTP header based on name from the response.
* wp_remote_retrieve_headers() – Returns all of the HTTP headers in an array for processing.
* wp_remote_retrieve_response_code() – Gives you the number for the HTTP response. This should be 200, but could be 4xx or even 3xx on failure.
* wp_remote_retrieve_response_message() – Returns the response message based on the response code.
So in this tutorial we will be using the wp_remote_get function to make the request to the web service API. After successfully connecting and getting back our JSON data, we will then use the wp_remote_retrieve_body function to grab just the body of the request and then parse the data. Normally, in basic PHP we would be using cURL but WordPress already has everything baked into the Core so we will be using those functions.

Lets get started. First what I am going to do is to create a new template in my present theme. So jump into your present theme’s folder and create a new file, I am calling mine rest.php. So now in my theme’s main folder I have a new file called rest.php. Now I am going to create the code so my new template will show up in my theme on the front end.  I am also going to name my new template Rest. So open up your new file called rest.php and place this in your new file.

<?php
/**
 * Template Name: Rest 
 *
 */
get_header(); 
?>
    <div id="content" class="full-width" style="padding-left: 100px;">
		<h3>WP_Http</h3>
		<?php

		/* our new code will go */

		?>        
	</div>
<?php 
get_footer(); 
?>

Now remember, my theme will be different than your theme. What I did was just copy one of my themes other template files and stripped everything out of the main content area, I left my get_header, get_footer and the main content div. OK, so now I have my new template file so I will be able to see the results on the front end.  Now, I will login into the admin side of my WP website, create a new page, and then choose the new ‘Rest’ template we just created.  Be sure and Save. Go to the front end, and you should see a new page that looks like your theme with just a heading of WP_Http (That is if you copied my code above. If you did not, then your page should be empty).

wphttp-start

OK, now we are ready to get down to coding. So far we created a new template for our theme, created a new webpage and assigned this new template to the page. Displayed the new webpage in the front end that will be displaying our work.

We first need to code the Request part. I will be using the Bitbucket API.  For information on BitBucket: Bitbucket

For more information on their APIs: Bitbucket API

We will be making a call using the Bitbucket API to get the names of my repositories I have on Bitbucket.

In order to do this example, you will need an account at Bitbucket. If you are one of those developers who keeps avoiding GIT and putting your code into repositories, maybe this tutorial will give you the push to start. This tutorial will also being using Basic Authentication, so you will need to use your own username and password. I decide to use a web service that makes use of Authentication because there are less of these types of examples out there. OK, so after reading the Bitbucket API documentation, I will be using this Endpoint:  https://api.bitbucket.org/1.0/user/

Now time to start coding the request part:

<?php
$url = 'https://api.bitbucket.org/1.0/user/';

$username = '*******************';

$password = '****************';

$headers = array( 'Authorization' => 'Basic ' . base64_encode( "$username:$password" ) );

$request = wp_remote_get( $url, array( 'headers' => $headers ) );

if(is_wp_error($request)) {
return false;
}
    			
$body = wp_remote_retrieve_body($request);

$data = json_decode($body);


?>

this code will be placed into my template page as such:

<?php
/**
 * Template Name: Rest 
 *
 */
get_header(); 
?>
    <div id="content" class="full-width" style="padding-left: 100px;">
		<h3>WP_Http</h3>
		<?php
            $url = 'https://api.bitbucket.org/1.0/user/';
            
            $username = ‘*******************’;
            
            $password = '****************';
            
            $headers = array( 'Authorization' => 'Basic ' . base64_encode( "$username:$password" ) );
            
            $request = wp_remote_get( $url, array( 'headers' => $headers ) );
            
            if(is_wp_error($request)) {
            return false;
            }
            				
            $body = wp_remote_retrieve_body($request);
            
            $data = json_decode($body);
        ?>
	</div>
<?php 
get_footer(); 
?>

 

$url is the Endpoint .

$username will be your username.

$password will be your password

$headers = array( ‘Authorization’ => ‘Basic ‘ . base64_encode( “$username:$password” ) );

$headers will be an array that holds our Authentication variables.

$request = wp_remote_get( $url, array( ‘headers’ => $headers ) );

$request: here we will use the WP HTTP API function wp_remote_get() and pass in our endpoint URL and Authentication credentials.

if(is_wp_error($request)) {

return false;

}

Here we just do an error check, to make sure we have not hit an errors so far.

$body = wp_remote_retrieve_body($request);

$body: here we again use the WP HTTP API and use the wp_remote_retrieve_body function which produces only the body of the web services call response.

$data = json_decode($body);

$data: here we just use the php function json_decode so we can use the data in our php code. Time to check and see if we are successfully.

place the code below in your file after this line:        $data = json_decode($body);

This will basically dump out our json array, if we were successfully in connection to the API.

echo '<pre>';
print_r($data);
echo '</pre>';

I use the pre tags so it will print out the JSON array into a more readable formatted result.

you can just use this if you want:

print_r($data);

This section of code is just for testing. If you followed along you should see your array of information.

Now, either delete those lines of code or comment them out.

Now time to Parse our data.

if(!empty($data)) {

echo '<ul>';
foreach( $data->repositories as $repo ) { 

    	echo '<li>';
		echo $repo->name;
		echo '</li>';
	}
	echo '</ul>';
}	

First we check and make sure that our $data array is not empty. If not then we start our list declaration.  Then using a foreach loop we loop through all instances of repositories that are in the array and print out the name of each repo, When complete, we close our list and exit.

Let’s break down our foreach loop. How did we come up with those names. Well $data is our array of data, and if you ran the print_r code you see how the data is arranged. The proper name is repositories. If we start to look down our array we can see that the proper name is name.

print-r-array

 

 

So we create the foreach loop as such:

foreach( $data->repositories as $repo ) { 

    	echo '<li>';
		echo $repo->name;
		echo '</li>';
	}

So if we did everything correctly we now have a list of our Bitbucket repositories names. To see in real-time, check out the page here:

[button color=” blue” size=”small” link=”http://hyperdrivedesigns.com/wp-http/” target=””]Demo Page[/button]

 

wp-http-final

FINAL CODE:

<?php
/**
 * Template Name: Rest 
 *
 * This is the template that displays information from a web service.
 *
 * @package foundationwp
 */

get_header(); 
?>
    <div id="content" class="full-width" style="padding-left: 100px;">
		<h3>WP_Http</h3>
		<?php
			$url = 'https://api.bitbucket.org/1.0/user/';
			$username = '**************';
			$password = '**************';
			$headers = array( 'Authorization' => 'Basic ' . base64_encode( "$username:$password" ) );
			$request = wp_remote_get( $url, array( 'headers' => $headers ) );
			if(is_wp_error($request)) {
				return false;
			}
				
			$body = wp_remote_retrieve_body($request);

			$data = json_decode($body);
			
			if(!empty($data)) {

				echo '<ul>';
				foreach( $data->repositories as $repo ) { 

					echo '<li>';
						echo $repo->name;
					echo '</li>';
				}
				echo '</ul>';
			}			
            ?>        
    </div>
<?php get_footer(); ?>

Turbulence – Bootstrap WP Theme

Turbulence – Bootstrap WP Theme is now ready for purchase. Go to Brag Themes to buy Turbulence and check out the rest of the Bootstrap themes. Grab a free Bootstrap theme will you are there.

Check out our latest WordPress Theme at
turbulence.website.

This WordPress theme is based upon the Bootstrap Framework, and uses the Redux Options Framework that allows anyone to put together an Awesome Website. There are so many features so check it out at Turbulence.

Using PHP Tags In WordPress Screencast

Check out the new screen-cast titled Using PHP Tags in WordPress Screencast. Here I do a brief overview of the PHP WordPress Template Tags that are used in building WordPress themes. This screencast was created for Learnable. Learnable, is SitePoint’s sister website for learning web design/web development.

[button color=” blue” size=”small” link=”https://learnable.com/hub/play/86″ target=””]Watch Screencast[/button]

Google Calendar Link Plugin Released

Finally! Google Calendar Link Plugin Released!

Another Small Simple WordPress Plugin: Google Calendar Link Plugin is now ready for download. To see the plugin in action and to get more information just go under the WordPress Plugins menu and Click on Google Calendar Link Plugin. In order to download the plugin, just register at our website and then go to the Plugins Download Page. From this page you can download any of our Small Simple WordPress Plugins.

Pantheon – The Next Generation of WordPress hosting

pantheon

Anybody in the WordPress design or development world has probably heard of Drupal and when you think of Drupal you think of Pantheon. Well, Stop The Clock! Pantheon now has the platform framework for WordPress. Now, WordPress developers and designers can concentrate on building plugins, creating themes and let Pantheon worry about dealing with all of the complexities of hosting. Coming from a job where I worked on Drupal and WordPress websites, I knew the greatness of Pantheon. So when I heard that Pantheon was going to support WordPress, I was excited! Now, I strictly work on WordPress and have been able to become one of the first WordPress developers to join Pantheon and I would like to tell you about Pantheon from a WordPress developers prospective.

Pantheon provides many different pricing options: Free plan(Developer Sandbox): You can get a Pantheon account, create your WordPress sites and start coding. Now, if you want to have a custom domain you will have to upgrade to a paid plan. Paid plans range from personal, all the way to some major Enterprise plans. So from small to large, Pantheon can handle it.

So after you create an account you can log in to your dashboard and start spinning up your WordPress sites. You can create a Brand New site or import an existing WordPress site.

 

Now after you have your site up and running you will be in your development environment.

 

So your website will begin in development mode, then you will push it to the testing environment and then when your website is ready, Go Live! Pantheon comes with a host of cool features and options. Pantheon supports GIT and SFTP. So if you are a GIT person, you are in luck. If you still have not yet took the leap into GIT, you can still use a FTP client(like FileZilla) that supports SFTP. Just drag and drop your files from your local to your pantheon server. Or, if you have an editor that allows connection to remote sites, you can connect directly to your Pantheon server. Pantheon also keeps you informed of your GIT commit status.

 

As a WordPress developer, I created my WordPress test website which resides in the development environment. I can start coding my custom plugins for my customers. Now, I would like them to take a look at it and do some testing. So I can push my website over to the testing environment. With just a click of a button, Pantheon will clone your development website and database over to the testing environment. Now, I send my customers my testing URL and let them play around with the plugin. While they are doing some testing, I can still continue to work on the plugin(s) in the development environment without effecting the testing website. This is awesome. This works great for WordPress designers also. You can push your code over to testing, let your customers play around with your present work while you still continue to code away on your development site. Say goodbye to your localhost, say goodbye to trying to get Wamp Server or MAMP Pro up and running, say goodbye to dealing with adjusting your PHP settings, let Pantheon deal with all that while you get back to work developing plugins or designing themes. I tested connecting to my Pantheon websites using DreamWeaver and Sublime Text 2 editors without any issues. I am loving not having to deal with my localhost anymore.

Pantheon also keeps you informed about your server status, your database size, backups, and PHP error log. Pantheon also comes with a backup service and you can even have a Security setup on your development environment. You can use Custom domains and SSL certificates. Need access to your database, no problem. I just got the connection information, opened up MySQL Workbench, entered all of my credentials and I am in my database. Have a team of developers, Pantheon can handle it. They have a multi-dev environment for teams of developers.

Pantheon offers everything a WordPress developer/designer needs for their WordPress hosting. WordPress design agencies, WordPress development agencies, WordPress Theme companies, any business that uses WordPress can benefit from using Pantheon. Oh, by the way, did I mention Customer Service. Their Customer Service is awesome. You can email the founders and top Officers of Pantheon directly, that should tell you something. These guys care about their product and care about their customers, Bottom Line! So if you are looking for some new WordPress specific hosting, give Pantheon a try. Go on over to getpantheon.com (this is not an affiliate link), create your Free Sandbox account and give it a test drive. If Pantheon supports their WordPress platform like they do their Drupal platform, (which I am pretty confident they will), you will be more than satisfied. So if you are in the market for the next generation of WordPress hosting, ‘Put A Pantheon It!’

Adding Dashicons to Custom Post Types Admin Menu

OK, WordPress Designers and Developers. I finally have figured out how to use the new Dashicons. If you do not know what the Dashicons are, go to the website here. With WordPress getting a nice overhaul in the admin theme, Dashicons are used throughout the new admin theme. So I just got finished making a new plugin which required a custom post type. So I wanted to give the new post type a cool new Dashicon then the default pin. So here are the steps:

1. In the custom post type script where you normally state the menu_icon this is what your syntax will be (see highlighted line # 22):

function create_orl_books()
{
register_post_type( 'orl_books',
  array(
    'labels' => array(
    'name' => 'ORL books',
    'singular_name' => 'ORL Book',
    'add_new' => 'Add New',
    'add_new_item' => 'Add New ORL Book',
    'edit' => 'Edit',
    'edit_item' => 'Edit ORL Book',
    'new_item' => 'New ORL Book',
    'view' => 'View',
    'view_item' => 'View ORL Book',
    'search_items' => 'Search ORL Book',
    'not_found' => 'No ORL Book found',
    'not_found_in_trash' =>
    'No ORL Book found in Trash'
    ),
    'public' => true,
    'menu_position' => 15,
    'menu_icon' => 'dashicons-[book]',    'supports' => array('title', 'editor', 'thumbnail')
    )
  );
}

2. OK. Now we know where to place the code correctly, how do we get the Dashicons? Go to the Dashicons website and find the icon that you would like to use.Click on the icon and go back to the top of the Dashicon home page and click on copy html. There you will see what the CSS class is and get that name and place it in the brackets on the menu-icon line.

3. Save your css page and then refresh your admin webpage and this is what you should see:

WordPress Beginners Tutorial – Building a Theme Options Page

wordpress logo

WordPress Beginners Tutorial – Building a Theme Options Page

After many hours of searching the web, looking for some great WordPress admin theme options page tutorials, I have found a lot of different methods which became confusing and complicated. So after many hours of learning and understanding how to create an options page, and after including an options page for some of my clients, I decided to create the most BASIC tutorial on this issue. I will try to be as basic and simple as possible so beginners can follow along easily. This tutorial expects the user to have a beginner background in html, php and WordPress. This tutorial will show the very minimal things to code to get a working options page in your WordPress theme. After you start to understand and learn the basics, then you can branch out and find some more advanced tutorials. So here we go. To set this up, say we are creating a brand new WordPress theme called Blitz. If there already is a WordPress theme called Blitz, this tutorial has no relationship to that theme and is purely by coincidence. Of course with our new Blitz theme, we have a folder called Blitz under our themes folder and includes the very basic files that are required for a WordPress Theme. The files we have in our Blitz folder are index.php, header.php, footer.php, style.css and functions.php.

Continue reading