Tag Archive: PHP

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


// Register the script first.
wp_register_script( 'some_handle', 'path/to/myscript.js' );

// Now we can localize the script with our data.
$translation_array = array( 'some_string' => __( 'Some string to translate' ), 'a_value' => '10' );
wp_localize_script( 'some_handle', 'object_name', $translation_array );

// The script can be enqueued now or later.
wp_enqueue_script( 'some_handle' );


And then using JavaScript OOP method to access the variable:

    alert( object_name.some_string) ; // alerts 'Some string to translate'

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.

	// Pass the PHP variables to JS
function js_vars() {
	<script type="text/javascript">
		var dir = "<?php echo plugins_url("", __FILE__); ?>";

add_action("wp_head", "js_vars");

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

$(".ast_gplus img").attr("src", dir + "/Google.png");

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:

$fruits = array("apple", "banana", array("good", "well")=>"pineapple");

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

$fruits = array("apple", "banana", "pineapple"=>array("good", "well"));

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:
    update wp_posts set post_content = replace(post_content, ‘find this text’, ‘replace with this’);

    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

    update wp_posts set post_content = replace(post_content, ‘robbychen.com/oldBlog’, ‘blog.robbychen.com’);
  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

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:

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^(.*)$ index.php?url=$1 [PT,L]

However, the one in the pages folder is different:

<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteRule ^(.*)$ ../$1 [L]

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.

	// Variables configuration
$rootDir = dirname(__FILE__) . "/";
$mainDir = "pages/";
$appDir = $rootDir . $mainDir;
if (isset($_GET['url'])):
	$url = $_GET['url'];
	$path = $appDir . $url . ".php";
	$path = $appDir . "index.php";
if (!file_exists($path)):
	$path = $appDir . 'notfound.php';
	$title = "Page not found";

	// Set page title
	// First set the page title from the the title variable from the individual page if presented
foreach (file($path) as $content):
	if (strstr($content, "title")):
		if (strstr($content, """)):
			$quote = """;
			$quote = "'";
		$titleVar = explode($quote, $content);
		$title = $titleVar[1];
	// Process the URL as the page title if title variable is not set
if (empty($title)):
	$urlPath = explode("/", $_SERVER['REQUEST_URI']);
	$titleVar = (string)$urlPath[sizeof($urlPath)-1];
	$title = "";
	for ($i=0; $i < strlen($titleVar); ++$i):
		if ($titleVar{$i} == strtoupper($titleVar{$i})):
			$title .= " ";
	$title .= $titleVar{$i};
	$title = ucfirst($title);

	// Include the neccesary pages
include_once $rootDir . 'includes/header.php';
include_once $path;
include_once $rootDir . 'includes/footer.php';

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.

Creating an even Simpler Framework than MVC Framework – Part 1 (Updated)

Update: I rewrote the code for the framework and added page title generation as well, take a look at part 2.

After building and digging through the source of the simple MVC framework provided by Anant Garg, I was able to discover the true nature of the MVC framework. Actually, I’m able to modify his framework to an even simpler framework which just use View and a little Controller in the MVC (Model-View-Controller) with no database connectivity.

The primary use for the MVC pattern is to work with the database. However, sometimes we don’t need to use database to creating a web site. According to my own knowledge, the Model is used to interact with the database and the Controller uses logical to process the database.

I stated that I need to use “a little” Controller because it also controls which page to display and sends it to the View.

In this simple framework (and perhaps all of the MVC frameworks), the most important file is .htaccess which controls the URL. Here is the content of the file copied directly from Anant’s post:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1 [PT,L]


Note that this .htaccess file needs to place in th root directory of your web site instead of public folder because we will be creating a framework that has no directory. You can create public folder or webroot folder if you want, but make sure to change the following code accordingly.

The above code converts the URL path to the url query. For example, the URL http://localhost/mvc/test would be converted to http://localhost/index.php?url=mvc/test.

Next step is to create the index.php file which used to process the url query:

	if (isset($_GET['url'])):
		$url = $_GET['url'];
		$path = "{$url}.php";
		$path = "home.php";

	include_once 'includes/header.php';
	if (file_exists($path)):
		include_once $path;
		include_once 'notfound.php';
	include_once 'includes/footer.php';

This is what I called “reverse include”, because I had always been include header and footer manually on every page until I found CakePHP MVC framework.

I also stated that this framework will not have any folder. Well, to include header and footer, you need to create an includes folder to place all the repeatable scripts, unless you really want to be disorganized :) .

Congratulation, you just created a mini framework. Note that this framework is used for small websites or personal sites where the database is not used at all. This means that it doesn’t have a back-end to edit the page directly on the server.

However, there is also an advantage to it. You don’t need to include the header and footer manually when creating a new page. It will include them automatically. It also can direct to the custom page if the specified page is not found.

About the title issue: I haven’t found a solution to set the title on individual page yet. Right now the title in the header is static. I will update this post once I find a solution to this issue.

Feel free to discuss this framework with me in the comment below.

Write CSS3 with Understandable Variables with LessPHP – Part 3

LessPHP allows you to use variables in your CSS stylesheet for the repeatable blocks of code.

In part 2, I provided you with the content of var.less. This part I will give you an example on how to use this .less file to write your own stylesheet. The provided example is based on the final project of this post on the Nettuts+.

First off, here is the folder structure for this example:

Example folder structure

Folder structure for the example

From top to bottom, they are:

css - folder

less - folder

lessc.inc.php in less folder - LessPHP compiler

main.less in less folder - source file to compile to CSS stylesheet

@import 'var';

body, html {

body {

#box {
  border: 1px dashed #666;
  margin: auto;
  cursor: pointer;
  position: relative;
 	:after {
	  content: '';
	  position: absolute;
	  bottom: 0;
	  left: 15%;
	  z-index: -1;
	> div {
    position: absolute;
    top: 0;
    left: 0;
    font: 45px/200px bold helvetica, arial, sans-serif;
    text-align: center;
  	:first-child {
	    position: relative;
  	  z-index: 2;
 :hover {
 	> div:first-child {
  	opacity: 0;
	div:last-child {

var.less in less folder - contains the LessPHP variables which I already provided it to you in part 2

index.php in css folder – contains the compile script which provided in part 1

main.css in css folder – contains the compiled CSS styles

index.php in root folder – contains the inclusion of main.css in css folder

Note that some of the code are directly copied from the above source. Also, in order to completely experience this example, you need to use Chrome or webkit compatible browsers.

Feel free to ask any question you have regarding the above code in the comment below.

Write CSS3 with Understandable Variables with LessPHP – Part 1


LessPHP is the PHP version of LessCSS, a CSS stylesheet language which is relied on Node.js web server. All LessPHP need is the PHP server.

In this part I walked you through the installation of LessPHP compiler and general folder structure for a one-page web app using LessPHP. In the next part, I will give you some CSS3 properties with parameters which have easy to understand variables.

The installation of LessPHP is easier than you think. After you download its source from GitHub, the only step is to copy lessc.inc.php into your web app folder and included in the page. Here is the basic structure for the folder:

Folder structure for the one-page web app

Folder structure for the one-page web app

Below is the explanation for each file and folder from top to bottom:

web app is the root of the web app.

styles contains lessPHP files and compiled CSS stylesheets.

less contains lessPHP compiler and less source.

main.less relates to main.css which I discussed below. It contains the styles information that will output to main.css.

var.less contains the lessPHP variable definitions which is imported to main.less using @import.

index.php in the styles folder is used to compile the less source to CSS stylesheet. It contains the following code:

// Convert LESS to CSS styles
include_once 'less/lessc.inc.php';
try { lessc::ccompile('styles/less/main.less', 'styles/main.css'); }
catch (exception $ex) { exit($ex->getMessage()); }

main.css is the compiled stylesheet.

index.php contains the code of your web app but first you need to include the index.php from the styles folder:

include_once 'styles/index.php'; // Include the LessPHP compiler in the beginning of this file

The above is general folder structure of mine for one-page web app. If you need to create a multi-page web app, you can create a include folder and include the lessPHP compiler to header.php or somewhere similar.

When you edit the stylesheet, you need to only edit the .less files and it will re-generate main.css file once the page is loaded.

In the next part, I will provide you the content of var.less which mentioned above that includes some CSS3 properties for your reference or you can use it as a template.

If you have any question about this part, post them in the comment below.

New Blog Title, New Logo

Note: As this post was written long time ago, I’m currently use Mac OS on the MacBook Air. Until I find a stable way to run Ubuntu on my MBA, I will stick to use OS X.

As you already saw, I changed the title for this blog from “Robby Chen Personal Blog” to “Ubuntu Web Coder “as well as the logo.

One reason for changing the blog title is because I’m going to stick to Ubuntu, specifically Lucid Lynx (10.04.1), since I depend on some PPAs to get the updates. Maverick Meerkat (10.10) just doesn’t work for me. I will wait until Natty Narwhal (11.04) is out and see. If this still won’t work for me, I will stay with 10.04.1 and wait for the next release… Anyway, you get the idea.

As most of you who read this blog in the past know, I used to write code in Netbeans until I discovered the hidden potential of gedit for being such a good IDE. That’s why I abandoned Netbeans and replaced with gedit in the new logo. And I renamed blog title specifically to “coder” because I would like to try writing the code in each post from now on.

Besides the gedit logo in the new logo, I have also included two groups of logos, GNU/Linux and PHP. The GNU/Linux logos include Linux penguin, Chrome OS, Android, and Open Source. The PHP logos include PHP, CakePHP, and WordPress. I also included just released HTML5 logo created by W3C. I regularly use these tools and talked and will continue to talk about them in this blog. That’s why I included them in the logo.

What do you think about the new logo, blog title, and background color?