WordPress Logo

WordPress Transients, a Simple Example

The first time I heard of WordPress Transients, it sounded scary. But after figuring out what they were, how to create them and what they were used for, it is a no-brainer to not use them in certain situations. According to the WordPress codex:

WordPress Transients API offers a simple and standardized way of storing cached data in the database temporarily by giving it a custom name and a timeframe after which it will expire and be deleted.”

“The Transients API is very similar to the Options API but with the added feature of an expiration time, which simplifies the process of using the wp_options database table to temporarily store cached information. “

“Advantage: Transients expire and Transients are inherently sped up by caching plugins, where normal Options are not.”

I build a lot of custom WordPress websites which uses custom database tables and I have to create custom database queries. This is a good option to use Transients API especially with database queries with multiple JOINS. Using transients will speed up the page loading since most likely a Transient will already be present with the results compared to making a database call each time the page is loaded.  According to the WordPress codex, “Using transients in your plugins and themes is simple and only adds a few extra lines of code, but if used in the right situations (long/expensive database queries or complex processed data) it can save seconds off the load times on your site.

There are three basic functions to use Transients, create or set, get and delete.

How do we create a transient.

set_transient( 'special_query_results', $special_query_results, 12 * HOUR_IN_SECONDS );

How do we get a transient.

get_transient( 'special_query_results' );

How do we delete a transient.

delete_transient( $transient );

 

Let’s take a look at a real world example. When working with Transients we want to always to a check to see if the Transient you are looking for exist and if not then you would create it as it is possible for the transient to not be available before the expiration time. For example, say you have a brand new page that does not get a lot of traffic and the code to create the transient has not run yet and then your code is looking for a transient on another page that is not there. Also, what if your Transient expired, you always need to run a check to if it exists first and if not then create it. Then the next time the page loads, the Transient should be available.

$routes = get_transient( 'cached_shipping_routes' );
if ( empty( $routes ) ) {
    global $wpdb;
    $routes_query = $wpdb->get_results("SELECT * FROM `shipping_routes` WHERE route_id  NOT IN  ('COLLEGE', 'AIRPORT', 'HOSPITAL', 'CIVIC CENTER', 'MEDICAL CLINIC')");
    set_transient( 'cached_shipping_routes', $routes_query, 6 * MONTH_IN_SECONDS );
 }
if ( $routes ) {
    echo '<select id="shipping_route_ddl" name="shipping_route_ddl" class="shipping_select_ddl" aria-label="Select A Route"><option value="select">SELECT A ROUTE</option>';
    foreach ( $routes as $route_value ) {
         echo '<option value="' . esc_attr( $route_value->route_id ) . '">' . esc_attr( $route_value->route_short_name ) . ' / ' . esc_attr( $route_value->route_long_name ) . '</option>';
    }
    echo '</select>';
}

Let’s break down the above code:

Line 1: we attempt to get the transient titled ‘cached_shipping_routes’ and set it to a variable called routes.

Line 2-5 we do a check to see if the $routes variable is empty. if it is empty then this transient is not available thus we are going to run our database query and then set the results to a variable called $routes_query. We then create the Transient using set_transient.  We pass in the title of the Transient, then the $routes_query variable which holds the results from our database query and lastly we set the Expiration time.

If the $routes variable is NOT EMPTY, then the Transient we are looking for is there, and then we use the $routes variable which holds our Transient value from Line 1 and we create our dynamically generated select element.

Now this query is not large query with multiple JOINS but the database table is large with a lot of rows and we are excluding certain rows with specific route ids. This allows our page to load faster. Of course the first time the Transient is NOT available, the page will load slower this time but after that the page will load faster, especially if you use some type of caching.

Here is a reference from to the WordPress Codex on Transient.  https://codex.wordpress.org/Transients_API

There is also an excellent plugin from Pippen Williamson called Transients Manager which allows to view all of your websites Transient from the admin.

https://wordpress.org/plugins/transients-manager/

Blog, WordPress,
JavaScript Logo

Creating Event Handlers in JavaScript

Over the past 5 years, I had to redesign multiple websites and use some of the previous codebase as to not have to start from scratch. One thing I noticed a lot was previous developers using inline JavaScript click event.

for example,

<button id="reset_btn" class="primary" onClick="resetPage();">RESET</button>

Best practices suggest not to use this type of JavaScript inline event handlers if you can but create an Event Hander that will listen for the button click that will then run the JavaScript function.

Here we just create the normal HTML button.

<button id="reset_btn" class="primary">RESET</button>

Here is our JavaScript. We use the JavaScript window object to load the reset button Event Handler. Now, when the button is clicked, the resetPage function will execute. This is just a simple example that will reload the page.

 
window.onload = function()
{
    document.getElementById('reset_btn').onclick=function(){resetPage();};
}

function resetTP() 
{
    location.reload();
}  

 

Blog, JavaScript,
WordPress Logo

Dynamically populating ACF Checkbox Field from Custom DB Query

ACF (Advanced Custom Fields), the greatest WordPress plugin on Earth allows us do some many things. Every time I work on a new project, which I always use ACF, I find a new use or something new the plugin can do. This time there was no exception. I needed to query a custom database table and then display these options/values in an ACF checkbox field which were attached to a Custom Post Type. So I jumped over to the ACF documentation and found this snippet of information for the acf-load_value Filter which Elliot so kindly created for us to alter a fields data.

https://www.advancedcustomfields.com/resources/acf-load_value/

If you do not understand or know what WordPress Filters are continue reading or you can skip down to just view the sample code below. WordPress has Hooks where developers can hook into the code base without having to edit/hack the core code base. There are two types of WordPress hooks, Actions and Filters. From the WordPress Codex, Action Hooks are triggered by specific events that take place in WordPress, such as publishing a post, changing themes, or displaying an administration screen. An Action is a custom PHP function defined in your plugin (or theme) and hooked, i.e. set to respond, to some of these events. Filter hooks are functions that WordPress passes data through, at certain points in execution, just before taking some action with the data (such as adding it to the database or sending it to the browser screen). Filters sit between the database and the browser (when WordPress is generating pages), and between the browser and the database (when WordPress is adding new posts and comments to the database); most input and output in WordPress passes through at least one filter. WordPress does some filtering by default, and your plugin can add its own filtering. So WordPress has its own Hooks and usually good WordPress developers create custom Hooks in their plugins for other developers to use.

So using the acf-load_value filter, I can query the Database, get my result sets and inject these values into my ACF field.


function acf_load_routes_effected_field_choices( $field ) {
	global $wpdb;
	$routes = $wpdb->get_results( "SELECT * FROM shipping_routes" );
	$field['choices'] = array();
    if($routes){        
        foreach( $routes as $route_value ) {       
            $field['choices'][ $route_value->route_id ] = $route_value->route_short_name.' / ' .$route_value->route_long_name;
        }
    }
    return $field;
}
add_filter('acf/load_field/name=routes_effected', 'acf_load_routes_effected_field_choices');

 

Blog, PHP, WordPress,
WordPress Logo

Dealing with multiple React dom entry points in WordPress Theme Development

After getting so excited with the new WordPress script package which includes the ability of not having to manually setup Webpack and Babel for rapid Gutenberg Block creation, I ran into an issue when I started building a WordPress theme. I have multiple files which I wanted to include different individual React Components in different areas. For example, I wanted a React component in my main blog file page which would consume the WordPress REST API and load all of my posts on the page. But then I wanted another React component to consume the REST API to display a single post on a single post template. If I tried to use the default index.js file, I could not load multiple React Components all in the index.js. I need multiple entry points so I can attach my multiple Blog Posts component to a template with a dom element of app and then a different Single Post React Component to a different template file with a dom element of singlePostApp.

What is the number one rule in development? “DON’T HACK CORE”. Since Webpack comes bundled in WordPress core, I could technically edit (hack) the webpack.config.js file in core but it would get overwritten on the first WordPress update. So again Kudos to the WordPress team for thinking ahead. We can extend the webpack.config file.  They thought ahead and realized that some people would need to customize, edit, or change the webpack.config file and that is what we are going to do in this post.

Here is the documentation from WordPress on extending Webpack:

https://developer.wordpress.org/block-editor/packages/packages-scripts/#provide-your-own-webpack-config

So here is my src folder structure which resides in my themes root file.

Theme src folder structure

 

I have my two main entry point js files.

I then created a new webpack.config.js file in the themes root directory. Here is where I extended the WordPress core Webpack file. I tell my new extended Webpack file to use my two different entry point js files.

const defaultConfig = require("./node_modules/@wordpress/scripts/config/webpack.config");

const path = require( 'path' );

module.exports = {

  ...defaultConfig,

  entry: {

    ...defaultConfig.entry,

    index: path.resolve( process.cwd(), 'src', 'index.js' ),

    SinglePostApp: path.resolve( process.cwd(), 'src', 'SinglePostApp.js' )

  }

};

After running the build command and there are no errors in the terminal, there will be multiple build files.

Theme build folder structure

Here are my main two entry js files. Notice one is attached to a file with a dom element of app. It imports one of my React Components called PostList. My second one is attached to a dom element of singlePostApp which imports a different React Component called SinglePostApp.

index.js

React Entry File

SinglePostApp.js

React Entry File

Now after extending the Webpack config file, I can add different React Components all throughout my theme. I just need to update my custom webpack.config,js file in my theme’s root folder with the new entry point files. Again, time to start creating some cool React Components for my WordPress theme!

 

JavaScript, React JS, WordPress,
WordPress Logo

WordPress React Ready with Webpack and Babel bundled in core

Thank you WordPress Team! Webpack and Babel now come packaged in WordPress, time to start building some custom Gutenberg Blocks without spending time, a lot of time setting up your local build setup. Being a PHP developer first, dealing with all of the new JavaScript and the React framework, I spent many hours trying to just set up my local WordPress instance just to start building.

Now with the newest version of WordPress 5.2.1, Webpack and Babel come baked into WordPress core ready to compile your ESNext JavaScript code.

Let us take a look and build a very basic block using these new features.

In my plugins folder, I am going to create a new directory using the terminal in my VSCode editor.

mkdir my-esnext-block

then lets cd into the new directory

cd my-esnext-block

now let’s create a package.json file in this directory run this command in your terminal:

npm init

 

npm-init code

The next step is to install the packages required. You can install packages using the npm command npm install. If you pass the –save-dev parameter, npm will write the package as a dev dependency in the package.json file. The –save-exact parameter instructs npm to save an exact version of a dependency, not a range of valid versions. See npm install documentation for more details.
So using the terminal, and you are still in your new plugin directory run:

npm install --save-dev --save-exact @wordpress/scripts

After installing, a node_modules directory is created with the modules and their dependencies which will include everything you need to start coding using React JS and ESNext JS.

Also, if you look at the package.json file it will include a new section:

"devDependencies": {
  "@wordpress/scripts": "3.1.0"
}

The @wordpress/scripts package handles the dependencies and default configuration for Webpack and Babel. The scripts package expects the source file to compile to be found at src/index.js, and will save the compiled output to build/index.js.

With that in mind, let’s set up a basic block. Create a new folder called src and a new file called index.js with the following content:

Since this tutorial mainly covers the wordpress scripts block package, we will just use the block code from the wordpress github repo for examples of gutenberg blocks located here:  https://github.com/WordPress/gutenberg-examples

const { __, setLocaleData } = wp.i18n;
const { registerBlockType } = wp.blocks;

const blockStyle = {
  backgroundColor: "#900",
  color: "#fff",
  padding: "20px"
};

registerBlockType("gutenberg-examples/example-01-basic-esnext", {
  title: __("Example: HDD Basic (esnext)", "gutenberg-examples"),
  icon: "universal-access-alt",
  category: "layout",
  edit() {
    return <div style={blockStyle}>Hello World, step 1 (from the editor).</div>;
  },
  save() {
    return (
      <div style={blockStyle}>Hello World, step 1 (from the frontend).</div>
    );
  }
});

now lets register our block
we will create our plugins main php file index.php and place the following code in this new file:

<?php
/**
 * Plugin Name: Gutenberg HDD Examples Basic EsNext
 * Plugin URI: https://github.com/WordPress/gutenberg-examples
 * Description: This is a plugin demonstrating how to register new blocks for the Gutenberg editor.
 * Version: 1.0.2
 * Author: the Gutenberg Team
 *
 * @package gutenberg-examples
 */
defined( 'ABSPATH' ) || exit;
/**
 * Load all translations for our plugin from the MO file.
*/
add_action( 'init', 'gutenberg_examples_01_esnext_load_textdomain' );
function gutenberg_examples_01_esnext_load_textdomain() {
	load_plugin_textdomain( 'gutenberg-examples', false, basename( __DIR__ ) . '/languages' );
}
/**
 * Registers all block assets so that they can be enqueued through Gutenberg in
 * the corresponding context.
 *
 * Passes translations to JavaScript.
 */
function gutenberg_examples_01_esnext_register_block() {
	if ( ! function_exists( 'register_block_type' ) ) {
		// Gutenberg is not active.
		return;
	}
	wp_register_script(
		'gutenberg-examples-01-esnext',
		plugins_url( 'build/index.js', __FILE__ ),
		array( 'wp-blocks', 'wp-i18n', 'wp-element' ),
		filemtime( plugin_dir_path( __FILE__ ) . 'build/index.js' )
	);
	register_block_type( 'gutenberg-examples/example-01-basic-esnext', array(
		'editor_script' => 'gutenberg-examples-01-esnext',
	) );
  if ( function_exists( 'wp_set_script_translations' ) ) {
    /**
     * May be extended to wp_set_script_translations( 'my-handle', 'my-domain',
     * plugin_dir_path( MY_PLUGIN ) . 'languages' ) ). For details see
     * https://make.wordpress.org/core/2018/11/09/new-javascript-i18n-support-in-wordpress/
     */
    wp_set_script_translations( 'gutenberg-examples-01-esnext', 'gutenberg-examples' );
  }
}
add_action( 'init', 'gutenberg_examples_01_esnext_register_block' );

 

Now we need to use the wordpress scrips package and convert our React code in our index.js file for the build process. In the package json file we need to tell it what to use to build. Add the following to your package.json file in your new plugins folder.

"scripts": {
  "start": "wp-scripts start",
  "build": "wp-scripts build"
},

for development, you can use ‘npm run start’
for production, you can use ‘npm run build’

Final package.json file:

{
  "name": "my-esnext-block",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "wp-scripts start",
    "build": "wp-scripts build"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@wordpress/scripts": "3.2.1"
  }
}

Now using the terminal run this command:

npm run build

After using  npm run build command and there are no errors in our terminal we should have a build folder with our index.js file located in there.

so here is what our plugin file folder structure looks like:

Plugin folder structure

We should be able to see our new block in the editor

 

 

And here it is on the front end:

front end block view

Again, Kudos to the WordPress team for getting this build package into core and saving everyone so much time. This new feature  allows us to start building new Gutenberg blocks much quicker without the headache of setting up Webpack. Theme developers can start using it also. Just create a package.json file in the theme root directory, create a src/index.js folder file in the theme root, and start writing your React code.  Be sure you are in theme root when you do all of your terminal commands.

JavaScript, React JS, WordPress,
JavaScript Logo

Add Typewriter Text to your webpage

How to add Typewriter Text to a webpage with some easy javascript.
First let create a div where the text will be displayed:
<p id="typewriter"></p>
Here is the simple JavaScript:
<script>
var i = 0;
var txt = 'I am Typewriter Text. See me type.';
var speed = 50;

function typeWriter() {
if (i < txt.length) {
document.getElementById("typewriter").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
</script>
JavaScript,
WordPress Logo

WordPress Developer Helper Functions For Locating Files

WordPress comes with helper functions to located, files, images, documents within your plugin or theme.
Here is a list of some of the most used functions developer use:

1. get_theme_root() : returns the address of the theme installation directory.
2. plugins_url() : returns the address of the plugins directory.
3. get_template_directory_uri() : retrieves the URI to the current theme’s files.
4. admin_url() : provides the address of the WordPress administrative pages.
5. content_url() : indicates where the wp-content directory can be found.
6. site_url() : returns the address of the website.
7. home_url() : returns the address of the website.
8. includes_url() : provides the location of WordPress include files.
9. wp_upload_dir() : indicates the directory where user-uploaded files are stored.

Blog, WordPress,
Internet Explorer Logo

How to target IE / IE Specific CSS styles

OK. Let’s take a look at the IE changes over time. When we wanted to target IE browsers in order to use IE specific styles, we would normally create a CSS specific file(normally titled: ie.css) with the IE specific CSS styles. We would then use conditional commenting as such:

<!--- code for using different IE stylesheets --->
 
 <!--[if IE 8]>
       <link rel="stylesheet" type="text/css" href="http://test.com/css/ie8.css" />
 < ![endif]-->
 <!--[if IE 9]>
    	<link rel="stylesheet" type="text/css" href="http://test.com/css/ie.css" />
 < ![endif]-->

Then if the browser was IE, it would load the specific IE css file with the IE specific styles.

Then came the changes. IE 10 drops conditional commenting. Then IE 11 decides to change their User Agent. So now what?

In order to target IE and render the IE specific CSS styles we had to do a work around. So this is a quick example of how to accomplish this task in today’s modern IE browsers.

1. Create a small piece of JavaScript which I place in my header files which grabs the user agent of the browser.

<script type="text/javascript">
var doc = document.documentElement;
doc.setAttribute('data-useragent', navigator.userAgent);    
</script>

2. Then in my CSS style sheet, (you can create an IE only css file or just place the IE specific styles in your main css file) I create my specific styles for each of my IE Browsers. So as of today, I normally target back to IE 8. This is now my code looks like in my CSS style sheet. Unfortunately, these styles get loaded for every browser but the styles are only used for their specific IE versions. Normally, I usually do not have a lot of specific IE styles just a small amount so the little bit of extra payload is not that big of deal having to be loaded in every browser.

/* ==========================================================================
   IE STYLES
   ========================================================================== */
/************* IE 11 STYLES *****************/
html[data-useragent*='rv:11.0']  .socialmediaicons {
    width: 480px;
}

/************* IE 10 STYLES *****************/
html[data-useragent*='MSIE 10.0']  .socialmediaicons {
    width: 480px;
}

/************* IE 9 STYLES *****************/     
html[data-useragent*='MSIE 9.0']  .socialmediaicons {
    width: 480px;
}

/************* IE 8 STYLES *****************/
html[data-useragent*='MSIE 8.0']  .socialmediaicons {
    width: 480px;
    margin-right: 35px;
    margin-top: -50px !important;
}

Now the next big question is, what will the NEW Microsoft Edge browser have in store for us. No worries about the later versions of IE as they will still be around for some time in support of legacy software. So using the above solution will still be in play for a while.

Please feel to leave comments and let me know what you think or if you run into any issues.

ASP.NET, Blog, Cross Browser Compatibility,
WordPress Logo

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).

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 Github API.  For information on Github: Github

For more information on their APIs: Github API

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

In order to do this example, you will need an account at Github. 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. OK, so after reading the Github API documentation, I will be using this Endpoint:

https://api.github.com/users/username/repos

Now time to start coding the request part:

$username = 'redsoxfan2499';
$url = 'https://api.github.com/users/'.$username.'/repos';
$request = wp_remote_get( $url );

if(is_wp_error($request)) {
	return false;
}

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

<main id="main" class="site-main" role="main">
	<?php if ( have_posts() ) : ?>
        
        	<?php /* Start the Loop */ ?>
        	<?php while ( have_posts() ) : the_post(); ?>
        
        	<?php
        		/** get page content **/
        		the_content();
        	?>
        
        	<?php endwhile; ?>
        
        	<?php endif; ?>
							
		<h3>WP_Http</h3>
		<p>This page is used for my WP HTTP API Tutorial.
			Check it out:   
		<a href="https://hyperdrivedesigns.com/simple-wp-http-api-tutorial/">WP HTTP API Tutorial</a>
		</p>
		<?php
			$username = 'redsoxfan2499';
			$url = 'https://api.github.com/users/'.$username.'/repos';
            $request = wp_remote_get( $url );
								
            if(is_wp_error($request)) 
            {
			    return false;
			}

			$body = wp_remote_retrieve_body($request);

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

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

					echo '<li>';
					echo $repo->name;
					echo '</li>';
				}
				echo '</ul>';
			}				
		?>
</main><!-- #main -->

$url is the Endpoint.
$username will be your username.

$request = wp_remote_get( $url );

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

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 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 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:

Demo Page

FINAL CODE:

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

get_header(); 
?>
	<div class="container">
        <div class="row">
        	<div id="primary" class="col-lg-12 col-md-12">
        		<main id="main" class="site-main" role="main">
							<?php if ( have_posts() ) : ?>
        
        			<?php /* Start the Loop */ ?>
        			<?php while ( have_posts() ) : the_post(); ?>
        
        				<?php
        				/** get page content **/
        				the_content();
        				?>
        
        			<?php endwhile; ?>
        
        		<?php endif; ?>
							
							<h3>WP_Http</h3>
							<p>
								This page is used for my WP HTTP API Tutorial.
								Check it out:   
								<a href="https://hyperdrivedesigns.com/simple-wp-http-api-tutorial/">
								WP HTTP API Tutorial
								</a>
							</p>
							<?php
								$username = 'redsoxfan2499';
								$url = 'https://api.github.com/users/'.$username.'/repos';
								$request = wp_remote_get( $url );
								if(is_wp_error($request)) {
									return false;
								}

								$body = wp_remote_retrieve_body($request);

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

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

										echo '<li>';
											echo $repo->name;
										echo '</li>';
									}
									echo '</ul>';
								}				
								?>
							<br/><br/>
							</main><!-- #main -->
        	</div><!-- #primary -->
				</div><!-- end row -->
    </div> <!-- .container -->
<?php get_footer(); ?>
Blog, PHP, Web Development, WordPress,