Tag Archive: 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() 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() 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() 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.


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.

A little Nested foreach Tip


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

The above code outputs the following:


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


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:

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:

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

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:


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?

Access PHP values within JavaScript in WordPress

WordPress JavaScript

When using JavaScript to access PHP values in WordPress, the official way, according to the WordPress Codex, is

And then using JavaScript OOP method to access the variable:

I know that the PHP function is used for translating the values across different languages (such as English to French), and for transferring multiple values to JS as well. However, for transferring simple value such as the location of a file in a plugin and some numbers, you can use inline JS directly.

And you can access the variable(s) in JS:

Of course, you need to use wp_localize_script PHP function if you follow OOP (Object Oriented Programming) practice.

Have you used wp_localize_script before to transfer such simple values to JavaScript? And for what reason, code consistency by using OOP, have many variables to transfer to JavaScript, or else?

A Quick PHP array Tip


Here is a small tip for the nested arrays in PHP.

When using nested arrays, make sure not to include an array in a key. Only include an array in a value.

For instance, the following code results in the “illegal offset type” error:

Here, the problem is in the third pair of the fruits array. Here is the right way to do it:

Have you experienced this issue before, or did you already know this type of error?

Disable PHP in Uploads issue in iThemes Security

Disable PHP in Uploads

Caution when enabling the “Disable PHP in Uploads” option under System Tweaks section for iThemes Security. It will prevent all the files containing “php” in the filename from displaying, whether or not it’s in the filename section or the extension section. For example, example.php will display the not found page, and lessphp.png will also display the not found page.

Disable PHP in Uploads

“Disable PHP in Uploads” option located in the iThemes Security settings page. Click the image to enlarge.

The solution is to avoid using “php” in the filename when uploading images while the option is enabled. And if you still want to use “php” in the filename, you can disable the Disable PHP uploads option, however it’s not recommended.

Image is broken

Do you have this issue that the image is not showing up after you uploaded the image like the screenshot on the left?

Then this might be the problem.

If you still have questions regarding this issue, please leave a comment below.

Replace a phrase in several posts for WordPress

MySQL replace function

I talked about changing the URL paths of images and links for the old posts will be based on the 404 not found error generated through traffic, one by one. Apparently, this was a bad decision. I don’t expect the traffic go up so quickly after I added these old posts. It seems that they still are more popular than my new ones. Therefore, I decided to search for a solution to replace some parts of url for the links (and images) in the old posts with the current url format so that it can direct them to the correct file locations.

During the research, I stumbled across MySQL replace function. I thought that it could come in handy when replace certain phrase within some posts, such as old links and image links. And here are the steps:

  1. Login to cPanel of your web host.
  2. Find and login to phpmyadmin.
  3. Go to the database which your WordPress installation resides.
  4. Click the SQL tab and type the following codes into the text box:
    Replace “find this text” with the text or phrase or whatever you want to be replaced, and replace “replace with this” with the text you want to replace. For instance, mine was
  5. Click Go button and the text is changed in the database.

Now that almost all the links were fixed (at least I think), I still will continue monitoring the 404 errors to see which links are missed from the above code until there are no more 404 errors.

If the above code could not work for you, you can’t understand one or more of above steps, or you have other solutions to replace the text across multiple posts, leave a comment below.

Creating an even Simpler Framework than MVC – Part 2

Creating an even Simpler Framework than MVC – Part 2

I discussed a little bit about this mini-framework in part 1. Today I rewrote the whole code for the index.php to be more configurable, and I added another folder for storing PHP pages. And yes, it includes the automatic page title generation.

It’s up to you to create other folders for the includes, images, and other files, but the PHP pages folder is a must have. Without this folder, the framework will grab the original page without process through the framework.

Let’s begin.

I need to first introduce the basic folder structure for the framework:

Note that I’ve included lessPHP inside the css folder to make writing styles easier.

The .htaccess file in the root folder is exactly the same as part 1‘s:

However, the one in the pages folder is different:

As those of you who understands the Apache better knows, the above code acts like access rejection. It means that whenever someone tries to access the pages folder or one of the files within it, this code will automatically rewrite the URL to the root folder. Note the difference between rewrite and redirect.

The pages folder is kinda like public or webroot folder, except it’s only used for PHP pages, not for images, stylesheets, Javascripts, or any other files.

Now the most important file, index.php. This file is placed in the root folder, and contains the most important code in the whole framework. I also added page title generation in this file as stated before.

As you have noticed, I’m using URL to auto-generate the page title. You can also set the page title for each page using the $title variable.

The $mainDir variable is configurable, so you can rename the pages folder to whatever you want.

That’s it. If you don’t count the img, css, and js folder and files inside them, the files for the framework would be total of 7 files.

Here is the completed files.

If you have any issues working with this mini-framework, leave a comment below and I will happy to help you.