Archive for the ‘WordPress’ Category

How To Add A DZone.com Button To Your WordPress Blog Posts Automatically

Saturday, May 30th, 2009

After previously adding the DZone.com voting buttons manually to each post (which you really don’t want to do every time as you need to set the post URL manually for the index page) I have modified the JavaScript provided by DZone and integrated some code into the WordPress files so that a button is added automatically on each post now just like the button to the left of this text.

Uploading The Modified JavaScript File

I noticed that DZone isn’t currently sending a cache header on every JavaScript request and that the snippet you are given to integrate into your post redirects via a 302 header to the real file. If you have 5 DZone buttons on your blog’s homepage (if you are displaying 5 posts) that means 10 additional HTTP requests to DZone.com that take time and delay the page loading process.

If you have already integrated the JavaScript snippet provided by DZone you should remove it now otherwise you will get two buttons per post. Just download this file and upload it to a directory of your choice on your server. You may even use the WordPress uploader but write down the final path to the JavaScript file as you need to enter it in the next step.

Now open Appearance > Editor in the WordPress Admin Panel on the left hand side and click on header.php on the right hand side. Add the following line somewhere within the <head> of the document:

<script src="/js/dzone.js" type="text/javascript"></script>

Replace “/js/dzone.js” by the path where you have uploaded the dzone.js file before. Then click on “Update File“.

Adding The Button To Every Post

After saving click on the link “single.php” on the right side just as you did before with the header.php file. Depending on your chosen WordPress theme the HTML code may look more or less like this:

<div class="entry">
<?php the_content('<p class="serif">Read the rest of this entry &raquo;</p>'); ?>

Just between the opened <div> tag and the following <?php tag insert the snippet code:

<span style="float:left;margin:0 10px 10px 0"><script type="text/javascript">dzone_show_linkbox('<?php the_permalink(); ?>', '<?php the_title(); ?>', null, 1);</script></span>

Thus the modified code will look like this:

<div class="entry"><span style="float:left;margin:0 10px 10px 0"><script type="text/javascript">dzone_show_linkbox('<?php the_permalink(); ?>', '<?php the_title(); ?>', null, 1);</script></span><?php the_content('<p class="serif">Read the rest of this entry &raquo;</p>'); ?>

Save the file by clicking on “Update File” afterwards.

Repeat this step for the index.php file and you’re done.

If you are using the WP Super Cache plugin or any other caching plugin you may need to clear the cache otherwise you won’t see the modified pages. When using WP Super Cache select Settings > WP Super Cache on the left side and then on the “Delete Cache” button on the page.

After reloading your blog’s homepage or any article page you will now see a DZone button just like this article does.

Google Trends Gadget Reveals Interesting Weekly Search Behavior

Friday, May 22nd, 2009

Although Google Trends is nothing new embedding it on a website is. I just tried some Google Trends searches analyzing user search behaviour and some interesting  facts arose. When performing these searches you should always be aware that keywords may not have one meaning only thereby distorting the graph. So you shouldn’t use Google Trends to compare “apple” and “pear” because of the well known company named “Apple”.

The disadvantage of the Google Trends Gadget is that you cannot give a specific date for displaying statistics, only relative values so these graphs will surely look different each day you are looking at them on this page.

It’s Monday: Searching For A Doctor

It is interesting to note that these search terms have the highest search volume on Mondays and then fall off over the next days. In contrast to what one might expect there is not an even distribution over the weekdays and a lower search volume on weekends.

Weekend Priorities

As the weekend arrives other search terms dominate the search engine queries. The following graph shows some queries that show this weekend trend.
I just picked some words that came to my mind which are mostly unambiguous and have a comparable search volume.

Rather Even Distribution

As one might expect general search terms have a more even distribution over the week but a slight drop on weekends is noticeable which is somewhat expected.

Opposing Trends

Using Google Trends you can  also find somewhat opposing trends like this comparison of restaurants vs. hotels.

Browser Wars? Not Really.

This graph shows the distribution of the search queries for different browsers. With this graph you also need to keep in mind that the words “opera” and “safari” are ambiguous.

Using The Gadget For Your Own Statistics

You can of course use this information to find out when to launch specific campaigns or when to expect a higher AdWords search volume. If you want to see current statistics on Google search volumes for different keywords you can now simply create a page and embed the Google Gadget several times on that page just like I did on this page. So you don’t have to go to the Google Trends website to search for different terms one by one.

Embedding The Google Trends Gadget On A WordPress Blog

If you are using WordPress and want to embed these statistics on your blog you need to have a plugin for WordPress that enables the use of IFrames like Embed Iframe otherwise for security reasons WordPress will silently eat your IFrame code.

This is a sample code for embedding the gadget into your WordPress blog if you have installed the Embed IFrame plugin (you need to remove the space in front of the “iframe” word at the beginning and just before the closing bracket):

[ iframe http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/trends_gadget.xml&source=imag&up_is_init=true&up_cur_term=firefox,internet%20explorer,explorer,opera,safari&up_date=mtd&up_region=US 330 250 ]

tweetthis-15

Saving Link Juice With Nofollow For The “Twitter for Wordpress” Plugin

Wednesday, May 20th, 2009

I have just recently enabled the Firefox Addon SearchStatus while on my blog’s homepage. I was amazed that the Twitter For Wordpress plugin doesn’t add rel=”nofollow” to the My Latest Tweets widget (see on the right in the sidebar).

Therefore I have just added the corresponding code to the plugin’s PHP file and thought I should share this information because it might really be useful for other people.

Adding rel=”nofollow” to the Twitter links

First make a backup of the file wp-content/plugins/twitter-for-wordpress/twitter.php and save it as twitter.org.php in the same directory. Afterwards open the file twitter.php and modify the code as highlighted here. You need to scroll to the right to see the highlighted code:

function hyperlinks($text) {
    // match protocol://address/path/file.extension?some=variable&another=asf%
    $text = preg_replace("/\s([a-zA-Z]+:\/\/[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)([\s|\.|\,])/i"," <a rel=\"nofollow\" href=\"$1\" class=\"twitter-link\">$1</a>$2", $text);
    // match www.something.domain/path/file.extension?some=variable&another=asf%
    $text = preg_replace("/\s(www\.[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)([\s|\.|\,])/i"," <a rel=\"nofollow\" href=\"http://$1\" class=\"twitter-link\">$1</a>$2", $text);
    // match name@address
    $text = preg_replace("/\s([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]*\@[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})([\s|\.|\,])/i"," <a rel=\"nofollow\" href=\"mailto://$1\" class=\"twitter-link\">$1</a>$2", $text);
    return $text;
}
function twitter_users($text) {
       $text = preg_replace('/([\.|\,|\:|\¡|\¿|\>|\{|\(]?)@{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/i', "$1<a rel=\"nofollow\" href=\"http://twitter.com/$2\" class=\"twitter-user\">@$2</a>$3 ", $text);
       return $text;
}

After you have added the code save the file, upload it you your server and you’re done.

If you are using the WP Super Cache plugin be sure to empty the cache so that all pages are updated.

tweetthis-15

How To Achieve Maximum Website Performance (Part 1)

Saturday, May 9th, 2009

The idea for this article came to my mind when I was wondering why twitter.com is so slow sometimes. When looking at the source code of my profile homepage on Twitter I was really shocked because I still cannot understand why such a reputable company with so many users does not use all of the methods and processes available to increase the performance of their website.

But first things first. Before you’re going to analyze your website to find out what you can optimize to increase the performance of your website you need to install the following addons and Firefox of course.

I have also compiled a comprehensive list of Firefox addons for developers but you only need the addons listed above to follow the steps described in this article series.

1. Finding The (Maybe Not So Usual) Suspects

It is important that you empty your browser cache first.

Now just open the website in your Firefox you wish to speed up.

At the bottom of the browser in your status bar you will see information collected by the lori addon.

Screenshot of "Life Of Request" info

Screenshot of "Life Of Request" info

Time To First Byte

The first value shows you how long it took for the first byte to arrive. On this blog’s homepage it took just about 0.157 seconds. If you have dynamic data on your page and maybe even database queries on your site the value may actually be much higher.

This value is important to optimize your code on the server side. If you see something like more than 0.5 seconds or even a value greater than one second you know that you have to optimize your server-side code (more on that later).

Total Load Time

The second value shows how long it took until all of the elements on the page had been loaded - this includes embedded images and everything else - even external scripts and embedded video players. If this value is higher than about two to three seconds you know that you need to optimize the code on the client side.

Total Number Of Bytes

The third value shows the total number of bytes transferred which also includes images, scripts etc. Depending on your site and your target audience this value may be quite high but in most of the cases it should not exceed 200K (if your site is a blog it may be up to 500K in my opinion).

Number Of HTTP Requests

The fourth value shows you how many separate HTTP requests to a server were required. Your goal should be to minimize this number. At the time of writing there were 37 HTTP requests required on this page (and 5 requests on reload which is shown in the screenshot) which is quite a large value. Every HTTP request (especially if the request goes to different servers) results in a delay of your page being displayed.

There is no rule of thumb regarding this value - it depends on the nature and contents of your site but it should always be as low as possible.

2. Optimizing The Time To First Byte

If the time to first byte value is quite high you need to optimize your server-side code. As there is no general rule for all the different backends, applications and content management systems I can only give general recommendations here yet I will also show you how to decrease this value if you are using WordPress on your own server (not the hosted blogs at Wordpress.com).

Static Page

If the page you are trying to optimize is a completely static page (like a real HTML file) and the value is relatively high I would interpret this as your server being too slow or being under a high server load. You should check this with your webhost as a static page should be delivered by webservers in a very short amount of time.

Dynamic Page

If your page is a dynamic page developed in PHP, Perl, Ruby-On-Rails, JSP or any other web development language or system there may be much to optimize depending on the nature of your page.

Do you have many content on your website that is retrieved dynamically?

You may for example have the latest comments by users in your forum, on your blog or the latest images or postings on your page. If you are not caching these contents (or the page) on your server yet just ask yourself the following question:

What is the access-to-update ratio, i.e. how often is the specific page accessed by someone and how often do you change or update the contents?

If you have many people accessing your page yet you only update it hourly or even daily or weekly you should implement caching on your server. You may for example just update the contents on the page every X minutes from the database or you may use what I call intelligent caching where you only update cache files if the content has changed. This is actually what I am using on most of my own sites: when a new user joins the cache file containing the HTML code for the “new users” snippet is deleted. Whenever someone then accesses the page the PHP script on the server checks if the cache file is available and loads it in that case. If it is not available it is created just-in-time, cached and will be used as long as it exists.

Implementing a caching algorithm is however very dependent on the language your code is written in and depends on your framework or application so I cannot go into detail on that matter, regretfully, as there is not a one-fits-all solution.

WordPress

I am using WordPress on this blog as well (as you might already have guessed) so I can give you some advice on how to optimize your pages.

I have seen many plugins for WordPress that have not been developed with getting lots of traffic in mind. Some retrieve the data from an external source (like your Twitter feed) on every single page request which not only increases load time it also means that your blog may be unavailable if Twitter (or any other source a plugin may be using) is down. This also leads to a huge amount of traffic to the external sources. You should check if the plugins you are using are requesting dynamic content from external sources on every single reload of a page.

Remember: whenever you access such a blog page data is retrieved from the external source before the page is displayed to the user (because it is server based). If these pages would be cached on the server for a limited amount of time this problem would be solved (to the most part).

There is actually a great caching plugin available for WordPress. It is called WP Super Cache and can be downloaded or installed directly from within WordPress. It decreases the load time of your WordPress pages dramatically because with the default installation WordPress pulls all article data on every request from the database so the database is really your bottleneck if you are getting lots of traffic to your site. WP Super Cache not only caches the pages it is also very intelligent in that it regenerates cache files automatically if you update your posts.

More info on WP Super Cache is available on this page as well.

This concludes the first part of the series. Continue to read the second part of this series.

tweetthis-15

Maintenance Page For Your WordPress Blog With Bots In Mind

Sunday, April 19th, 2009

I have just read this article from SmashingMag (#4) regarding a maintenance page for your WordPress blog which you could use while you’re upgrading or maintaining your blog. This quick hack is impressive yet it fails to take into account search engine bots.

Depending on how often crawlers like GoogleBot visit your website you should really think about your search engine rankings. Don’t forget: bots are not able to (at least not yet) understand the page they are accessing. If e.g. GoogleBot revisits your blog to index an article and finds a 302 redirect to your maintenance page this may lead to problems which in the worst case might mean that your maintenance page is being indexed and your previous article content lost for Google - at least as long as your maintenance page is up.

According to Google you should instead return a website with a 503 HTTP status code.

So let’s look at the original code by SmashingMag to put into your .htaccess file:

RewriteEngine on  
RewriteCond %{REQUEST_URI} !/maintenance.html$  
RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123  
RewriteRule $ /maintenance.html [R=302,L]  

The problem lies in the 302 redirect. So let’s just create a maintenance page telling GoogleBot to revisit our website in 30 minutes - you should of course add more informative text than I did to the page:

<?php
    $minutes = 30;
    header("HTTP/1.0 503 Temporarily Unavailable");
    header("Retry-After: ".$minutes*60);
?>
<html>
<head>
<title>Maintenance</title>
</head>
<body>
<h1>Maintenance - Please come back later in approximately <?php echo $minutes; ?> minutes.</h1>
</body>
</html>

Now the mod_rewrite rules in the .htaccess file need to be modified as well (assuming the file above would be saved as maintenance.php in the document root directory):

RewriteEngine on  
RewriteCond %{REQUEST_URI} !/maintenance.php$  
RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123  
RewriteRule $ /maintenance.php [L]  

That’s all - you’re done. After you have finished your maintenance work you just need to disable the rewrite rules by prefixing each line with a “#” symbol.

tweetthis-15

“Tweet This” WordPress Plugin Phones Home

Sunday, April 19th, 2009

Before installing any WordPress plugin for security reasons I always examine the plugin source code which is not a problem for me given my ten years developing in PHP. However I don’t expect the usual WordPress user to have this kind of knowledge most of which don’t even have any experience in PHP at all.

Thus when I was just reading the source code for the Tweet This plugin I was shocked to see that on both activation and deactivation of the plugin it  automatically transfers the following information to the developer’s website:

  • URL of your blog
  • Tweet This version
  • status (activated, deactivated)
  • number of posts in your blog
  • title of your blog
  • description of your blog
  • language of your blog
  • your email address
  • Tweet This plugin settings
  • WordPress version

This is actually the code snippet taken directly from the source code - no, I didn’t add the “Big brother” there, that’s how it’s written in the code:

// Big brother is watching.
function tt_phone_home($status) {
    global $current_site; global $wpdb; $wpv = get_bloginfo('version');
    $siteURL = $current_site->domain; $blogURL = get_bloginfo('url');
    $title = get_bloginfo('name'); $email = get_bloginfo('admin_email');
    $description = get_bloginfo('description');
    $lang = get_bloginfo('language');
    $posts = number_format($wpdb->get_var("SELECT COUNT(*)
    FROM $wpdb->posts WHERE post_status = 'publish'"));
    $settings = $wpdb->get_var("SELECT option_value
    FROM $wpdb->options WHERE option_name = 'tweet_this_settings'");
    $phone = tt_read_file('http://th8.us/ttph.php?s=' . $siteURL . '&b=' .
        $blogURL . '&v=1.3.9&u=' . $status . '&p=' . $posts . '&t=' .
        urlencode($title) . '&d=' . urlencode($description) . '&l=' .
        urlencode($lang) . '&e=' . urlencode($email) . '&w=' . $wpv .
        '&x=' . urlencode($settings));
}

So if you don’t want all this information to be transferred to the developer prior to activating the plugin you should simply add a “return;” right after the function definition leaving the rest untouched.

function tt_phone_home($status) {
  return;

That way the function will return right away and not calling any URL at all. I’m not telling that the developer is doing anything harmful with that plugin yet I don’t see any reason in transferring this information to his server.

tweetthis-15