retrieving tags and counts from WordPress blog

A website I’ve been working on has a WordPress blog included in it. The site is not using WordPress as the CMS, just as one section. While the blog is sub-foldered (e.g. http://%5BSITENAME%5D/blog/) there was still a need to refer to the tags elsewhere on the website, and link to them. While it would definitely be possible to reference components of the blog itself, and then call the function/s to get tags and counts etc, I decided to hook into the DB with some SQL and rock it from there.

After a quick explore of the WordPress DB, I pulled the tables and fields I needed to reference in order to get the results I desired. The query itself is pretty straight-forward:

SELECT wp_term_taxonomy.count AS count, AS name 
FROM wp_term_taxonomy, wp_terms 
WHERE wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id 
AND wp_term_taxonomy.taxonomy =  'post_tag';

Walking through this query step-by-step we have:

1 – SELECT wp_term_taxonomy.count AS count, AS name
choose the values we want, and from which tables, and give them an alias
2 – FROM wp_term_taxonomy, wp_terms
define the tables we are referencing during this query
3 – WHERE wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id
AND wp_term_taxonomy.taxonomy = 'post_tag';
put conditions to the results; here we want to make sure we are referring to the same term, and that it is a term of type ‘post_tag’

Implementation is very simple, the sample below is a delivery in PHP:

// connect to your DB
$sql = "SELECT wp_term_taxonomy.count AS count, AS name ".
"FROM wp_term_taxonomy, wp_terms ".
"WHERE wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id ".
"AND wp_term_taxonomy.taxonomy =  'post_tag';";
$taglinks = "";
$result = @mysql_query($sql);
if($result) {
	while($row = mysql_fetch_array($result)) {
		$tag = $row['name'];
		$count = $row['count'];
		$taglinks .= "<a href='http://[SITENAME]/blog/?tag={$tag}' 
				class='tag-link-{$count}' title='{$tag}' >
				{$tag}</a><br /> ";
	// close the DB connection for security, e.g.
	// mysql_close([CONNECTION]);

In my example, I have retrieved the tags and their counts and formatted them into absolute links which are styled based on the number of uses. This enables them to be displayed more prominently based on popularity for example.


client-side time with PHP and JavaScript

As part of upgrading functionality and statistical delivery with I’ve been looking at utilising client-side time. Obviously, PHP and other server-side languages do not have acces to this information. The solution is to use JavaScript and the ‘page-in-between’ method:

	$vars = "?";
	foreach($_REQUEST as $key => $val) {
		$vars .= $key."=".$val."&";
    echo "<script type=\"text/javascript\">"; 
    echo "localtime = new Date();"; 
    echo "document.location.href = '".$PHP_SELF.$vars."client_time=' 
            + localtime.getTime();"; 
    echo "</script>"; 
    // Process page as normal 

What this does is first check whether we have been given a parameter “client_time”. If we have, everything is grand and we can nmove on to rendering the page. If not then we need to iterate through all parameters/variables passed through to the page (either $_POST or $_GET [which has security implications – to be discussed]) and keep track of them as a string formatted for passing through a URL.

Then we use PHP to write a JavaScript function to the page before anything else. This script (running on client-side) gets the client’s current date and time (localtime = new Date();) before redirecting the browser to the same page ($PHP_SELF) with parameters appended ($vars."client_time=' + localtime.getTime();").

Then end result of this is that the client returns to the page, but this time brings with them their (client-side) time for use within your (server-side) functionality.

** Security Issue **

As I mentioned, there are security implications to this approach. By passing all $_REQUEST parameters through the foreach() loop and passing them back through as $_GET parameters (as they are contained in the URL itself) they are all visible and able to be manipulated by the client user or anyone who wants to. Any hidden parameters (ie $_POST) are made visible in this method. If you don’t have any $_POST parameters, or they are not security issues, then this should not be a problem; if there are secure parameters, then this method will not work for you.

If you want to use the time as a parameter, and the page request is coming from a form on another page of yours (hence the $_POST parameters), then you should add a hidden field to THAT form as so:

<input type="hidden" id="time" name="client_time" 
          value="a6d27182b9803699dc15f56e9c0e8eb4" />

with the following script being called at onload():

<script type="text/javascript">
function loadTime() {
var localtime = new Date();


<body onload="javascript:loadTime()" >

and then call the variable from there on the new page like so:

$clientTime = $_POST["client_time"];

This solution is more elegant than the ‘page-in-between’ method, and does eliminate the security weakness discussed.

Dynamic JavaScript population

Today I’ve been fiddling with adding options to a drop down list box dynamically using JavaScript (client side). Because this uses JS, it can also be conditional in terms of the options passed to the list (similar to using PHP on the server side to generate the options for the drop down list box dynamically).

The main function creates a new ‘option’ object and assigns values and text part of the option. This is the engine of that below:

function addOption(selectbox, text, value) {
	var optn = document.createElement("option");
	optn.text = text;
	optn.value = value;

Note that each time the function is called, it adds a new option to the list box. So we can add one option by calling the function once. Like this:

addOption(document.drop_list.week_list,"Monday", "Monday");

This way we can create a drop down list box of all the days of the week by calling the function each time for each day of the week. With this now you can easily create the list box. Efficiency then dictates that we should add another step to this by using one array of days of the week. So from the array of days we will loop through and add each day to the list box. Here’s the array set-up:

var days = new Array("Monday", "Tuesday", "Wednesday", "Thursday",
                               "Friday", "Saturday", "Sunday");

Now our array is ready with data, we will loop through the array by using for loop and then call the addOption function using the data of the array:

for (var i=0; i < days.length;++i) {
	addOption(document.drop_list.week_list, days[i], days[i]);

You can see with this array we will able to populate the drop down list box of days. Here is the simple code for html body tag and the form with drop down list:

<title>Dynamic List Population Example
function addOption(selectbox, text, value) {
	var optn = document.createElement("option");
	optn.text = text;
	optn.value = value;
function addOption_list() {
	var days = new Array("Monday", "Tuesday", "Wednesday", "Thursday",
                                       "Friday", "Saturday", "Sunday");
	for (var i=0; i < days.length;++i) {
		addOption(document.drop_list.week_list, days[i], days[i]);
<body onLoad="addOption_list()"> 
<form name="drop_list" action="yourpage.php" method="POST" >
<select name="week_list">
<option value="" >Week list</option>

stripping end characters from strings in PHP

I’ve been doing some updates to my URL shortening service ( recently, and some functionality I needed was to remove the last 2 characters of a string. Now, the normal way to remove the last character of any given string (as taught most places) is:

$str = substr($str,0,strlen($str)-1);

But, I was feeling like being out of the ordinary. After a bit of a rummage around, and some lateral/creative thinking, I came up with the following:

$string =  strrev(substr(strrev($string), 2));

I’ll break it down a bit below:

// first of all, reverse the string
// so, "thisIsAString" becomes "gnirtSSsIsiht"

$string = strrev($string);

// now, get the substring starting at the 3rd character
// so, "gnirtSSsIsiht" becomes "irtSSsIsiht"

$string = substr($string, 2);

// now, reverse the string again
// so, "irtSSsIsiht" becomes "thisIsAStri"

$string =  strrev($string); 

You can change the ‘2’ to be however many characters you wish to remove from the end of the string.

The one using strrev() is a lot faster then the ‘normal’ one for larger strings or many strings as it doesn’t require the script to count it’s way to the end of the string, but the first way is absolutely valid and works equally well so I would be remiss to not mention it.

embedding Javascript in PHP

One of the less known uses of external JavaScript is the ability to reference a PHP file instead of a .js file. This does seem to breach scripting etiquette, as we all "know" that server side and client side scripts are prohibited from interacting. Well, it turns out superficial exchange is allowed. Using external JavaScript, you’ll see how PHP and JavaScript can work together in a way you may not have thought possible, and to the great benefit of JavaScript.

The syntax to referencing a PHP file using external JavaScript is consistent enough with what we already know:

<script type="text/javascript" src="myscript.php"></script>

where myscript.php is either an absolute or relative path to a PHP script instead of the usual .js file. You can even pass parameters to the PHP script through the URL string:

<script type="text/javascript" src="myscript.php?param1=bob&param2=thomas"></script>

Your PHP script can then get to these parameters using the global variable $HTTP_GET_VARS[]. So you’re probably wondering at this point: "So what’s the catch?" Well, there is no catch really, just a few limitations. Since we are invoking the PHP script indirectly and via JavaScript, the final output of the PHP script needs to be valid JavaScript. Think of it as a dynamic .js file, bounded by the same limitations as a regular .js file. A normal PHP script called inside a PHP page can output raw HTML and modify the source code of the page. The JavaScript invoked version obviously cannot, but don’t worry, there’s plenty of what it can do.

Here’s a basic example of a PHP script- ip.php – being called by external JavaScript to do something that JavaScript alone cannot:



//"ip.php" example- display user IP address on any page

Header("content-type: application/x-javascript");


echo "document.write(\"Your IP address is: " . $serverIP . "\")";


And once called by external JavaScript:

<script type="text/javascript" src="ip.php"></script>

Output: Your IP address is:

In the above, we have a normal PHP script that writes out the IP address of the visitor when referenced using external JavaScript, with two important details:

  • A JavaScript header is sent at the very beginning to inform the page that our PHP script is outputting a JavaScript file.
  • Since the final output of our PHP script needs to be a valid .js file, whatever the PHP outputs must conform to valid JavaScript syntax. So to display the IP address from the perspective of JavaScript, the echo function above includes document.write() as part the content to send back to the page.

Notice how I didn’t output the JavaScript script tag itself <script></script>), as just like inside a regular .js file, this isn’t required nor valid.

The ability to reference a PHP script inside your external JavaScript can be very useful! It means your JavaScript now has access to once exclusive information on the server side, whether it’s the server time, the visitor’s IP address, a list of all the files within a certain directory, or mySQL database information. Now even regular HTML pages can utilize this dynamic information, as all they need is a JavaScript on the pages that in turn references the desired PHP script on your server or elsewhere.

Enjoy 馃槈

easy graphical dice generator in PHP

Just a simple little script which displays two die on screen. The faces are generated randomly, and are text-based, so no images required.





//Required code: This defines the dice array









//End required code



<font face='Lucida Console'>


<table border='1'>



<?php echo $dice[array_rand($dice)]; ?>



<?php echo $dice[array_rand($dice)]; ?>








php function to calculate the distance between co-ordinates

Just a little PHP function to calculate the distance between two coordinates. You can specify the units to be returned also.

function distance($lat1, $lon1, $lat2, $lon2, $unit) {聽
  $theta = $lon1 - $lon2;聽
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) *聽
    cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
  $dist = acos($dist); 
  $dist = rad2deg($dist); 
  $miles = $dist * 60 * 1.1515;

  $unit = strtoupper($unit);

  if ($unit == "K") {

    return ($miles * 1.609344); 

  } else if ($unit == "N") {
      return ($miles * 0.8684);
  } else {
        return $miles;

Usage is:

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "m") . " miles";

Hope that鈥檚 of some use to someone. You can co-ordinate it with a function to get the lat-long of a pair of zip codes, and then calculate shipping distance for example.