Web Development

WP REST API with PHP

WP REST API with WordPress

WordPress already created using PHP, so why do we need to make use of WP REST API with PHP? There are many reasons for that, including but not limited to:

  • A custom CMS solution specifically for a small group or company
  • A simple CMS using third party PHP libraries, such as CakePHP, or a custom coded library
  • A simple PHP web app

We can use WordPress admin as the main settings area, and use WP REST API to apply the changes.

It even can use as a WordPress theme to ease the theme development process. The first of several advantages comes to mind when using the API in a theme is the ability to use WordPress built-in functions. This makes design and development processes even easier by integrating WordPress features, such as Customizer and Widgets, into the theme without using large chunks of code (loop) to output the data from the database.

In fact, most of the functions we will be talking about in this post are WordPress functions. These functions are called WordPress HTTP API and are used to retrieve the content from outside domains. You can view their source code on the WordPress Trac. All of them use curl related PHP functions instead of simple file_get_contents().

wp_remote_get()

wp_remote_get() is one of two main functions in WordPress that is used to get information from an outside domain. Another function is wp_remote_post(), which is equivalent to submitting a form on a website, is a topic for another post.

The example below shows the usage of this function:

$response = wp_remote_get(“http://blog.robbychen.com/wp-json/posts”);

Make sure to replace the domain with yours.

wp_remote_retrieve_headers()

wp_remote_retrieve_headers() is the same as the $response[‘headers’] value from wp_remote_get() above. This is very useful compared to file_get_contents() because the json file from the WP REST API only shows the details of every post, not the overall details of all the posts, such as the total number of posts and how many pages there are if we use “posts_per_page” filter.

Although these can be calculated using a little script, however it’s not a good way to do it. Imagine there are thousands of posts on the site, using “posts_per_page=-1” filter and loop across all of the posts can slow down the site significantly, not to mention the server can eventually freeze, causing you to restart the server.

Here is the sample usage for this function:

$headers = wp_remote_retrieve_headers($response);

It returns an array containing all of the headers from the GET response. For example, $headers[‘x-wp-total’] and $headers[‘x-wp-totalpages’] are the total number of posts and the total pages number based on the “posts_per_page” filter respectively.

wp_remote_retrieve_body()

wp_remote_retrieve_body() is the same as the $response[‘body’] from wp_remote_get() function above. It’s basically like file_get_contents(), outputs the entire content of the target URL. For example,

$body = wp_remote_retrieve_body($response);

outputs the json document from /wp-json/posts of this blog. You can then use json_decode PHP function to convert the retrieved json document to a PHP object and use it within your project.

Disadvantages

Although using PHP to process WP REST API has above advantages, there are some disadvantages as well. Its main disadvantage is the loading speed for your pages.

When both WordPress and API-consume pages use PHP or other Server-Side Language on the same server, your web server uses large amount of memories and processing power to interpret the pages and output them to the browser. Thus, it may become slow or unresponsive depending on the hardware configuration of your server. For this reason alone, I recommend you to either consume WP REST API from a different hosting server, or use AJAX to consume the API. There are many tutorials out there on how to use various third-party JS libraries with WP REST API. There is even a NPM module for Node.js.

One WP REST API Usage Tip

WP REST API with WordPress

I have been experimenting with WP-API for the last several months and here is one tip I’ve discovered so far:

I mentioned in the previous post that I needed to setup separate sub-domains for serving WP-API and consuming it.

However, I’ve been consuming WP-API as part of a theme for the same sub-domain without any problem. In fact, there are actually some benefits to use it as a WordPress theme, such as:

  • The ability to use WordPress functions if you want to.
  • Utilize permalink structure without implementing your own router functions or using third-party library.
  • Take advantage of WordPress plugins ecosystem for the front-end.
  • Can be edited using WordPress Customizer.
  • And many other benefits …

Of course there are some disadvantages as well, such as slow performance of using too much plugins and use one server for both generate and process API is very resource intensive.

However, if you can’t get out of the WordPress environment just yet and still want to take advantage of WP REST API, this is the better way to go without using any third-party libraries which are not included in WordPress (it’s worth mentioning that jQuery is one of the third party libraries which is included in WordPress).

As WP REST API improves and moves more closer to the WordPress Core, we will be able to see more and more themes that use WP REST API.

Redirect old Permalink Structure in WordPress

WordPress Tips

By following this article on WPExplorer in the “Using the Simple 301 Redirects Plugin” section, you can redirect the URLs from the old permalink structure to the new ones one by one. However, this method doesn’t work if you want to redirect all of old links from other sites to your current permalink structure. For example, from example.com/2015/04/16/sample-post/ to example.com/sample-post/, unless you want to accept the hard work of entering all of the redirections by hand, which could contain thousands, even millions of URLs on your site.

Unfortunately in the mentioned article, the following instruction is not correct while adding the new redirection:

The Request field is the WordPress configuration for the Month and Name permalinks while the Destination field is the WordPress configuration for the Post name permalink structure.

Below are the correct values which need to be entered in each of these two fields:

Request field: /([0-9]+)/([0-9]+)/([0-9]+)/(.*)?$
Destination field: /$4/
Use Wildcards: check

The Request field is a regular expression. It means that there needs to be numbers in all characters in the first three slash pairs, and any characters after the last slash.

The Destination field is a reference variable to the last block of regular expression from the Request field, which is the fourth block. One block is determined by a pair of parentheses.

The Use Wildcards checkbox needs to be checked in order for the plugin to be imported to WordPress as a redirection statement containing regular expression.

For more information on the URL regular expression, you can read “Mod Rewrite syntax” where the above statements are inspired from.

You can also use a redirect WordPress plugin other than Simple 301 Redirects, which hasn’t been updated for the current WordPress version yet as of this writing. I’m using Redirection which supports the newest version of WordPress. The above settings are pretty much the same except the wording is different. For example, the Request field in Simple 301 Redirects is called “Source URL” in Redirection, etc.

Please leave a comment below if you have problem configuring the specific redirection plugin.

Publish WordPress Updates to Social Networks with IFTTT

Integrate IFTTT with WordPress

This post originally published on 02/23/2012. I don’t have the original version of the article anymore. The following content is recovered from web.archive.org. Since Wayback Machine only store HTML and links and doesn’t store any media files, the original images and videos has been removed and the corresponding content has been modified. Please read the original version over at Wayback Machine with image and video placeholders.

IFTTT is a web service that “put the Internet to work for you”. It stands for If This Then That.

If you have some programming knowledge, you know what it means. For instance, if you posted a tweet then post this tweet to Facebook, if you uploaded a video to YouTube then write a post on Tumblr, if today is raining then email you a warning, and so on. Basically, it means that if something happens then do the specified action. In “If this then that”, the “this” is a trigger and the “that” is an action.

This service is currently in beta, therefore it lacks many features. For example, it cannot allow users to create one trigger with multiple actions and vise versa. Because of this limitation, I created several same triggers with each different action:

IFTTT currently supports (exclude social network aggregators such as Boxcar and Buffer, as well as paid services such as Pinboard): Delicious, Diigo,Facebook, Flickr, Linkedin, Posterous, Storify, Tumblr, Twitter, and Zootool.

You can also create your own tasks by signing up for the service. As I stated in the beginning of this post, it’s like if … then statements in the programming world (maybe in real life as well), you can create some tasks just like scripting. For instance, you can write a tweet every 30 minutes using this service without knowing the Twitter API or writing any code.

Lessons Learned from editing a WordPress Plugin Code

WordPress Plugin

Since I wrote the original version of this article long time ago on 04/09/2012 and a lot had happened since then, I no longer have the original article. The following is what I have recovered from Internet Archive Wayback Machine. Note that since the Wayback Machine doesn’t store images, all of the image-referencing content below has been either modified or removed. Please read the version here if you need to see the original article with image placeholders.

In the theme and plugin sections of WordPress admin area, there is an edit button for each theme and plugin in order for you to edit the source code for them. I believe that some of you never touched this button to take advantage of the open source platform provided by WordPress just like me. I think that a lot of plugins to suit my needs, why would I edit somebody’s code?

Until recently, I was testing the Network Latest Posts plugin and noticed that it lacks the date/time display option. I searched for an alternate plugin but no single plugin can support the multisite. Finally I decided to dig through the source code of Network Latest Posts to customize my needs.

Here are the lessons I learned through editing its code:

  • The code can be improved

When I first read through the source code, I noticed a lot of code duplication. I wonder why the plugin developer didn’t place these repeated code into a function for easier access. I think I can improve its code by either move the duplicated code into a function, or convert it into object-oriented structure.

Thanks to the duplicated code in almost all the if…else statements, I used try and test method to modify a bit of code and test the plugin on the front-end. If the changes were not in effect, I reverted back to the original code and moved to the next section of code.

  • It’s important to have enough comments

The developer leaves many comments across the source code for this plugin. Thanks those comments, I saved lots of time by skipping the appropriate sections of code during the trying and testing process.

The comments are not just for other people to read through your code. I also learned that it’s easier to navigate through the code for me if I leave comments for the right sections of code.

  • Opportunity to learn others’ coding styles

One of the benefits of reading through other people’s source code is to learn their coding styles. If you never write a line of code for a WordPress plugin before, you don’t know the format of the code aside from your own coding style.

Through reading other people’s code, you can beginning to learn different coding styles from different developers. Not for long, you can develop your own coding style by combining the coding styles you learned.

  • Knowing the behaviors of the plugin

Another benefit of carefully reading the source code for each of the plugins you installed is to know the behaviors of the plugins. For example, the Network Latest Posts plugin saves the widget options to a database table. This can cause a bunch of useless database records if you installed and uninstalled many plugins.

With this knowledge, I can dig through the database with phpmyadmin to find and delete the records corresponding to the source code. Or I can write a PHP script to delete all of those records based on their code.

If you think a plugin has bad behavior, you can also check its code to see if the code can be modified to correct its behavior, or remove it from WordPress.

Do you know any other benefits for reading other ones’ source code? Please share them in the comments section below.

 

Google Forms to Google Docs with Apps Script

Google Apps Script

This past week I have had the opportunity to learn a new JavaScript-based language, Google Apps Script thanks to a tutorial provided by one of my clients.

It’s basically a scripting language used to integrate Google Apps with each other, such as Google Docs and Google Forms, Google Spreadsheets and Gmail, and so on.

One of my client’s requests was to create a PDF out of the form data once a Google Form is submitted. However, in order to do that, I need to create a separate template file with Docs, which is going to take very long considering it’s 7-page long when the form is printed out. And unfortunately, Google doesn’t support converting from Forms into Docs.

I won’t be copying the fields from a Google Form to a Google Doc one by one manually. Instead, I will be using Google Apps Script to loop through the field elements and copy them into a new Doc with a simple and readable format.

Here is the code I wrote:

/**
 * Adds a custom menu to the active form, containing a single menu item for
 * invoking checkResponses() specified below.
 */
function onOpen() {
  FormApp.getUi()
      .createMenu('Custom Actions')
      .addItem('Convert to PDF', 'formtopdf')
      .addToUi();
}

function formtopdf() {
  
  var form = FormApp.getActiveForm();
  
  // Create the required folder if it doesn't exist
  var rootFolder = '';
  var folderName = "Folder where the document will be generated in";
  if (DriveApp.getFoldersByName(folderName).hasNext() == false) {
    rootFolder = DriveApp.createFolder(folderName);
  } else {
    var matchedFolder = DriveApp.getFoldersByName(folderName);
    while (matchedFolder.hasNext()) {
      rootFolder = matchedFolder.next();
      break; // Only assign the first matched folder to rootFolder
    }
   }
  
  var contents = '\n';  // Initiate the contents variable with a new line
  
    // Get the title and description of the form and output to the document
  var formTitle = form.getTitle() + "\n";
  var subtitle = form.getDescription() + "\n";  
  contents += formTitle + subtitle + "\n";
  
    // Get all the responses that are submitted through the form
  var responses = form.getResponses();

  for (var j = 0; j < responses.length; j++) {
    var response = responses[j].getItemResponses();  // Get field names and corresponding values for the submitted data
    
    var doc = DocumentApp.create(formTitle + " for " + response[0].getResponse()); // Generate a document at the root of your account named title of the form plus the first value
    var docID = doc.getId();
    var docBody = doc.getBody();
        
    docBody.appendParagraph(contents);  // Add title and subtitle of the form to the document

    for (var item = 0; item < response.length; item++) {

      var title = response[item].getItem().getTitle(); // Get the field name
      var getResponse = response[item].getResponse();  // Get the submitted value
      
      docBody.appendParagraph(title + "\n").editAsText().setBold(false);  // Unbold the field text because of the loop
      docBody.appendParagraph(getResponse + "\n").editAsText().setBold(true);  // Bold the response text
      
      if (item == response.length - 1) continue;  // Prevent the output of horizontal line when it is the last item

      doc.appendHorizontalRule();  // Add a horizontal separator between items
     
    }

    doc.saveAndClose();  // Save the changes to the document and close it
        
  }

  // Notice to user that the generated PDF(s) are in the root of his Drive folder
  FormApp.getUi().alert(responses.length + " document(s) have been generated. They are available in your main Drive Folder.");
        
}

The above code should be self-explanatory since it’s well commented. If you still have some questions regarding the code, please leave a discussion in the comments below.

It basically loops through all of the form fields & values and outputs to the generated Doc. In the process, it makes values bold and places a horizontal line after each value to make the generated document more readable.

If you want to learn more about Google Apps Script, there are several ways. One is look through the sample code in the new project for each Google App. Another is to read and learn through the tutorials provided by Google. And another way is to just use the editor. The project editor has a nice auto-complete feature, and not to mention that the language itself has easy to understand syntax.

And of course, I will write more about the Apps Script while I’m learning it.

A little Nested foreach Tip

PHP

Here is a tip I found when fixing the database error for one of my clients.

<?php
	$row_parts = array("Monthly", "Special", "Transport", 10, 20);
	foreach ($row_parts as $row_part):
		foreach ($row_parts as $row_part_2):
			if ($row_part == $row_part_2):
				continue;
			elseif (!is_numeric($row_part) && !is_numeric($row_part_2)):
				continue;
			elseif (is_numeric($row_part) && is_numeric($row_part_2)):
				continue;
			endif;
			echo $row_part . "_" . $row_part_2 . "<br />";
		endforeach;
	endforeach;
?>

The above code outputs the following:

Monthly_10
Monthly_20
Special_10
Special_20
Transport_10
Transport_20
10_Monthly
10_Special
10_Transport
20_Monthly
20_Special
20_Transport

It uses a single array to store both words and numbers. Then combine them together through a nested foreach loop with an underscore to form reversible variables, reversible columns in this case.

I then can use these generated values to match the existing columns in the MySQL table and assign the corresponding variables to these values. For example, “20_Monthly” column would assign to $monthly_20 if “Monthly_20” column is undefined.

It saves client’s, other developers’, and my time to look for the source of errors in the future if the database column change from “20_Monthly” to “Monthly_20”, assuming that the format of the database column names remain the same.

This type of error for changing the name of database column is often occurred during the server migration. An unexperienced client would manually type the database entries by himself or by hiring an assistant, instead of using export and import features in phpMyAdmin.

Have you had similar clients? And how did you respond to them? Discuss them in the comments section below.

A Nice way to use the foreach Loop

PHP

I have been using this technique for a long time. Because I wanted to decrease the code I want to write, I developed this technique. Another reason that I found this technique helpful is that I don’t have to remember the whole snippets when learning a new trick.

Here is an example of the technique for the foreach loop I’m talking about:

$theme_mods = array(
	"footer_bg_color" => "#ADFF2F"
);
foreach ($theme_mods as $theme_mod => $default):
	$$theme_mod = get_theme_mod($theme_mod, $default);
	if (empty($$theme_mod)):
		$$theme_mod = $default;
	endif;
endforeach;

For those who are wondering what the above code is about. It’s used to apply the Theme Customizer settings to a WordPress theme. Here is the link to get_theme_mod() function documentation page, which is what the above code mainly about.

As the code shows, I use nested variables to assign each value in the loop to different variables for use outside the loop. For instance, the key “footer_bg_color” in the array would be converted into $footer_bg_color to provide value “#ADFF2F”.

I often use this technique on forms, where the fields need to be checked whether or not it’s empty. If so, assign an empty value. Otherwise, retrieve the value from the database and store it to the variable.

Here is the usage for the above code:

<style type='text/css'>
.site-footer {
	background-color: <?php echo $footer_bg_color; ?>;
}
</style>

In the future, when I need to add additional items to the theme_mods list, I just have to insert needed keys and values to the theme_mods array and add the key variables to the corresponding code.

I think that’s what others called DRY (Don’t Repeat Yourself) practice? I use it as a method for laziness to remember stuff :)

Do you practice DRY method often or rarely? And can you remember new techniques through using this method as well? Please share them in the comment. Thanks.

Don’t Generate Stylesheet Dynamically

WordPress Tips

During the early stages of my theme development process, I planned to use a PHP-generated stylesheet as the main stylesheet. Borrowing the WordPress native functions in wp-load.php, I would be able to use WP functions inside the PHP file which is the source file that the stylesheet would be generated.

For those unfamiliar with the above meaning, here is a line of code which needs to be placed in the first line of the stylesheet to be “dynamically generated”:

<?php header("Content-type:text/css"); ?>

And add the php extension to the filename of the stylesheet (ex style.css.php), as well as change the corresponding code in functions.php in your theme folder from:

wp_enqueue_style("shadow_leaves-style-custom", get_template_directory_uri() . "/css/custom.css", array("shadow_leaves-style"));

to:

wp_enqueue_style("shadow_leaves-style-custom", get_template_directory_uri() . "/css/custom.css.php", array("shadow_leaves-style"));

However, during my research of how to dynamically include wp-load.php instead of hard coding it, I discovered this article which talks about the bad practice of loading wp-load.php into external scripts, and generated CSS/JS in general.

Basically, for wp-load, it would allow the server to load two instances of WordPress, cause high resources usage on the server, in turn causing slow down of the site.

As for the dynamic generated scripts, it’s a bad practice because the server needs to generate the stylesheets / scripts every time one of the pages on the site is visited, as well as caching.

Overall, the primary reason for not using wp-load and dynamically generated files is to prevent slow down of the site.

Did you use PHP header() function to dynamically generate either stylesheets or javascript files or both before? And what’s your creative use of the header() function?