Latest Posts

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.

My New Forum is now Live

This post was originally published on 09/06/2010. It has been several years since then and I don’t have the original version of this post anymore. The following was copied from the Wayback Machine. The forum mentioned in this post no longer exists, although I’d like to restart such forum in the future. 

As you can see in the menu above, I installed a new forum using phpBB specifically for this blog. The forum will be used to discuss two main topics: GNU/Linux and web development, which are also the main topics for this blog. From now on, please post questions about any posts I’ve written on this blog to the corresponding topic over at the forum instead of posting comments here.

Actually, this is an experimental forum. I would like to separate the legitimate comments from the spam comments. Although I’ve used Akismet plugin to filter the spam comments, I don’t like it just because it decreases the performance of this blog. If this experiment was successful, I will disable the comment feature here and switch to the forum. Otherwise if spam posts were also discovered on the forum, the comment feature here will stay enabled.

So please visit my forum, introduce yourself, and post any questions you may have about GNU/Linux and/or web development. You may also ask questions other than these two main topics under the Blog topic. Thanks.

First Basic WordPress Theme

This article was copied from the Wayback Machine. It was originally published on 07/05/2010. A lot have been happened since then. Therefore, I no longer have the original version of the article, so does some of the links in this article. I marked the non-working links with a strikethrough line to differentiate them.

I was wondering around on WordPress functions reference page today and created a basic WordPress theme. The theme is static, neither could customize it nor add widgets. It uses seven main functions: get_header(), get_sidebar(), get_footer(), get_posts()get_categories(), wp_nav_menu() and bloginfo(). I copied most of the code for these functions from the sample code on these pages and modified them to use on the theme. You can preview the theme on this dummy blog. Or if you want, you can download the theme source files here.

As you can see the URL for the dummy blog, it is supposed to be a blog that talk about the inspirational quotes from the articles that I read. Since I haven’t read any article for the last month, I decided to temporarily make it as a dummy blog for my theme design. Its domain is also different from this blog. It is dot info instead of dot com. I own two domains, robbychen.com is for the public and robbychen.info is for my personal use. For example, I use analytics.robbychen.info for my sites analytics instead of using Google Analytics to increase the site speed.

My First Arch Linux Installation Experience

This article originally posted on 10/31/2010. The following was copied from Wayback Machine as I don’t have the original version anymore. The images in this article are also hosted on the Wayback Machine, so I removed “Click to Enlarge” in the article as there aren’t any enlarged version.

I first heard Arch Linux two years ago when I also discovered Linux from Scratch project. At that time, I didn’t have any experience on GNU/Linux nor the command line. I have finally chosen Ubuntu 8.04 because its good reputation on the Internet. However, I’m not interested in Ubuntu anymore since I recently upgraded to Ubuntu 10.10 and downgraded back to 10.04. Because my GNU/Linux skills have increased during the past years, I have decided to try Arch Linux.

During the installation process, I followed the installation instruction on the Arch Linux wiki:
https://wiki.archlinux.org/index.php/Beginners’_Guide

After transferring to USB using UNetBootIn, I have to change the USB drive label to ARCH_201005, otherwise it will display the following message:

To change the label, type “palimpsest” (without quote) in the terminal. Select the USB device on the left. Make sure to unmount the driver first, and then click the “Edit Filesystem Label” button to change the drive label to ARCH_201005.

And since I have both 64-bit laptop and 32-bit netbook, I downloaded the dual ISO which contains both 32-bit and 64-bit versions of the OS. After I copied the files to the USB drive through UNetBootIn and booted into the boot menu, the 32-bit and 64-bit selection items have no effect. The only option that works is the first “Default” one which is the 32-bit version. Because I want to install it on my 64bit-based laptop, I tried to figure out how to install the 64-bit version of Arch Linux. After looking into the boot options by press the tab key at the boot menu, I found out that all of the boot image files for each architecture are in the /boot folder. I also noticed that the working “Default” one is based on the two files in the root directory: ubninit and ubnkern. I think that these files are the same as the ones in the /boot/i636/ folder. Therefore I renamed these files with .32 extension and copied the only two files in the /boot/x86_64/ folder to the root directory with the same names as the ones with .32 extension. I then copied and renamed these files to the root directory with .64 extension for backup purpose. In the end, here is my current files in the root directory of the USB device:

Note that the two files without any extension (ubninit and ubnkern) are 64-bit files. I could delete them and replace with the .32 extension files in the near future once I decide to install Arch Linux on my netbook.

Since I was installing on the laptop, I have no wired Internet connection. I had to first connect to the Internet by using ifconfig, iwconfig, and dhcpcd utilities before the installation. Also, according to the wiki, I have to execute “dmesg | grep firmware” command in order to find out and install the appropriate wireless firmware during the installation.

Once I installed Arch Linux, I needed to solve the wireless auto-connection issue. Thanks to the netcfg wiki (https://wiki.archlinux.org/index.php/Network_Profiles#Connecting_automatically), I quickly solved the issue. One last thing that I’ve done is to remove the network daemon in the DAEMONS section of /etc/rc.conf file since I have loaded net-profiles daemon and I think the net-profiles daemon has the same usage as the network daemon.

After I installed GNOME and Compiz, I noticed the title bar on all the windows were missing once I enabled Compiz through fusion-icon. Thanks for the tip on the Arch Linux forum (https://bbs.archlinux.org/viewtopic.php?id=96991), I was able to regain the title bar. The solution is easy: open the ccsm (CompizConfig Settings Manager) and enable the Window Decoration plugin under the Effects section (make sure to enable Move Window and Resize Window plugins under Window Management section as well since they are basic window interaction elements). I also noticed that unlike Ubuntu and other similar distributions, all the Compiz plugins in Arch Linux are disabled by default since I installed GNOME from scratch.

The following are the reference sources that helped me during the installation:

If you have other tips on the Arch Linux installation and configuration process, please share them in the comments below.

Some Announcements and Site Updates

Blog updates

This is my second post for 2015. Here is the first post of the year which I published a while ago. I know this is late but here are some of the upcoming changes to the site as well as some announcements.

Lately I’ve heard a lot about WordPress API and how useful and powerful it is. I will be trying to use it on this blog since it contains more than enough posts and data for the API to use.

Here is how I will plan to use it: I will create a test subdomain to host the files, maybe blog-api.robbychen.com or something else. Then I will use JavaScript or a language other than PHP to create an API-generated blog. Ever since I installed WordPress, I have always felt that the WordPress-based site is very slow on my shared hosting account compared to the static HTML site, even with the help of caching plugins and CloudFlare. I will see if using this approach of converting the site to a static site with WordPress API will work.

In other news, I have experienced how easy is to create a simple mobile app through Phonegap. Yes, I just began to use Phonegap after some years of blog about it. The reason of holding back using Phonegap and Titanium Appcelerator was that I didn’t have enough inspirations to build a mobile app. To be honest, I still don’t have any app ideas. Hopefully I will be inspired during the learning process of Phonegap.

Talking about Titanium Appcelerator, I recently got invited to Appcelerator Platform perhaps due to my early registration of Titanium Appcelerator. By the way, I registered an account on the appcelerator.org during its early stage when there was not any educational material for this new platform at the time. However, I’m also yet to develop using Appcelerator due to the earlier mentioned lack of inspirations. Right now the website appcelerator.org has become the open source Titanium, where as appcelerator.com becomes Appcelerator Platform.

I’m also starting to use Google Webmaster Tools to manage this site. I have registered this site with Webmaster Tools since the creation of this site. However, due to the lack of knowledge for how to use Webmaster Tools effectively, I hadn’t been using it until now. The post I just published, “Redirect old Permalink Structure in WordPress“, was the solution I came up when browsing through the error log in Google Webmaster Tools. I also recovered some posts from Internet Archive Wayback Machine and republished them as new articles based on the data from the Webmaster Tools.

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.