Archive

Posts Tagged ‘PHP’

BotScout API for WordPress

December 21, 2012 Leave a comment

I have implemented the BotScout API for WordPress. You can use this code to check incoming registrations or comments against the BotScout API, to see if the account trying to register is a known spammer.

The code is posted as a Google Project. In a few days I will post some code samples showing how you can use this in your WordPress blog.

I am also working on a port of the code to MyBB. The code is compiled into a plugin pending approval on the MyBB website. It seems to be taking a while to approve. If I don’t get approval in a few days, I’m going to post it as a Google Project.

Advertisements
Categories: Uncategorized Tags: , , ,

How I sped up my WordPress blog

January 18, 2010 4 comments

I thought I’d share some tips on how I cut down the loading time for my blog. These tips might help someone out there make their WordPress blog (or any website) run faster. So far, using these techniques, I’ve shaved about 2 seconds off the loading time (when cache is empty) and for repeat visitors, the load time is under 7 seconds. Testing performed using OctaGate SiteTimer. As usual, FireFox and Safari browsers were much faster than Internet Explorer.

Compact (“minify”) your CSS, PHP, JavaScript (JS) and HTML Files

Removing whitespace, unnecessary lines, and useless code from these files will shrink file size, improving download time of these files, at the expense of (possibly) making the files slightly less readable. This is the easiest thing you can do with these files. There are even online “compressors” where you can upload or cut and paste your code, and it will spit out the compressed version, but I wouldn’t use that unless you understand the output. Obviously, it helps greatly if you understand CSS, PHP and so on, so you can edit and compact the code yourself.

Remove comments and commented code from your active files and paste them into local backup files. I keep them on my hard drive, where I can make notes on what they’re for, in case I do eventually need them. Some CSS files even have whitespace (empty spaces) at the end of the line. If you press the “End” key, you can see where the true end-of-line is, and backspace over it to remove the wasted space.

And as I’ve found the hard way, WordPress will still process code inside comments, while leaving it commented out. So commented code (especially with PHP or database calls) will needlessly waste processor time which could be used to display your webpage. Weigh the benefits of keeping commented code in your blog’s PHP files versus removing it to decrease file size and save processor cycles. Again, I remove unused code, comment it, and save it on my hard drive if needed later.

Google has an excellent Firefox addon called PageSpeed which can show you where your CSS is inefficient or unused.

See 10 Tips For A Smaller CSS File for specific examples of how you can shrink your CSS file.

Many PHP-based themes for WordPress also use comments and whitespace in excess. Removing the whitespace and concatenating lines where possible will result in smaller file sizes.

Your blog may also benefit from conditional includes, which will have the double benefit of shrinking your file size and providing dynamic content. The process is identical to the process for creating external JS files: include a link to the PHP file, and in that PHP file, remove the opening and closing PHP tags. Make it conditional by using if statements.

Move CSS to the top, and JS to the bottom

Page load time will also benefit if you move CSS links to the top of the page, and JS links to the bottom. Anyway, this is what Yahoo recommends in their webpage optimization guidelines. JavaScript that isn’t essential for the operation of the page (ex: visitor tracking code) should be placed in the footer or at the bottom of the page, so the main content can load first. If you run WordPress, this is easy; there are a few “move Javascript to footer” plugins. I use JavaScript to Footer.

JavaScript should also be externalized, to shrink overall HTML file size. See Reduce The Size Of Your HEAD and scroll halfway down for instructions on how to create external JS files.

Remove unnecessary Plugins, and make the remaining ones conditional

Are you using 10, 20, 30+ plugins? Some plugins are processed every time a page is loaded, even if they don’t actually do anything on that page. For example, some plugins hook into the wp_head function to place CSS or JS links in your header, which will be loaded on every page even if the plugin isn’t being used on that page.

Can you remove them, or find a “rollup” plugin that can do the work of two or three of your existing plugins?

A popular class of plugins for WordPress are the ones that interact with Google Analytics. The one used on my blog is Google Analytics for WordPress. This plugin automatically inserts your Google tracking code into your posts and pages. But I can duplicate the effort by simply pasting in Google’s tracking code directly into footer.php of my theme, thereby saving time having the plugin do it. Just go to your Google Analytics account and get the tracking code, and paste it into the PHP file. Sure, I might have lost some of the functionality of the plugin, but all I really need is the basic reporting function of my Analytics account.

Another popular plugin is Feedburner FeedSmith. This plugin detects all of the ways your feeds can be accessed, and redirects them to your Feedburner feeds. That way, you can aggregate all your subscribers under the FB feed, making your subscriber count more accurate, and making sure all your subscribers are seeing the same content.

But all I had to do to get rid of this plugin is visit What is My WordPress Feed URL? and then edit my .htaccess file to redirect the built-in WP feeds to my FeedBurner feed.

Redirect 301 /blog/feed/ http://feeds.feedburner.com/MyFeedName
Redirect 301 /blog/feed/rss2/ http://feeds.feedburner.com/MyFeedName
Redirect 301 /blog/feed/rss/ http://feeds.feedburner.com/MyFeedName

and so on.

I got rid of the Random Posts plugin by using code I found on the ‘net that returns random posts using a WordPress function.

I am also using the Similar Posts plugin (from the same author) in my post footer, and if I didn’t mind changing it to random posts instead, I could use the above code as well, and remove two plugins.

Check your plugins and see if any of them don’t need to run all the time. For example, if you run a plugin that allows visitors to email or print a copy of a post (ex: WP-EMail, WP-Print), you probably don’t need them to run if the visitor isn’t on a post page. Make them conditional instead. This sometimes requires direct editing of the plugin code itself.

  1. Deactivate the plugin
  2. Click the “Edit” link to edit the plugin file itself
  3. Wrap the entire plugin in an if statement that checks the current page. Don’t forget the opening and closing braces “{ }”
  4. Save the file and reactivate the plugin.

This will be most successful with plugins that write CSS or JS links inside your head tag, because this hack will stop them from doing so, thereby decreasing load time for pages where the plugin isn’t necessary. If you got a fatal error when editing/reactivating, or your blog breaks, or the fix simply doesn’t work, you might need to search the plugin file (deactivate it again first) and look for the section where the CSS or JS file is written, and add the above code there instead.

Once editing is finished, the plugin will only run where we want it. See WordPress Conditional Tags for a complete listing of conditional tags. Remember, you’ll need to repeat these steps every time a plugin is updated, because the hack will be wiped out by the update. It will be easiest if you deactivate the plugin, update it, then hack it, before reactivating it. Also, for those plugins you need to call manually in your template, you’ll want to go through your template files and wrap the function calls in an ‘if (function_exists(plugin_name))’ statement, because you’ll be deactivating it a lot and you don’t want your blog to break every time you need to update a plugin. In fact, I recommend you do this for all plugin function calls, even the ones you won’t be editing, because someday you might need to deactivate one.

Certain plugins don’t need to be running around the clock, and can be safely deactivated and reactivated when needed. For example, I keep the following plugins deactivated until I need them:

  • WordPress Database Backup
  • WordPress Automatic Upgrade
  • Optimize DB
  • Maintenance Mode

Although it might actually be better to remove them completely and reinstall them when needed, since all plugins (even deactivated ones) are checked to see if they apply to a current page. Very inefficient on the part of WordPress, but that’s the way it is, and this is an article about speed and optimization after all.

Use compression

If using WordPress on a Unix-based host, try and use mod_deflate or mod_gzip. Some cheap webhosts won’t allow you to use it, however, because they are resource hogs. As an alternative, you might be able to use PHP-based compression (zlib). It depends on your webhost. See Compress your WordPress website for more.

Got additional suggestions? Post a comment with your thoughts.

Categories: Tips Tags: , , , ,

Compress your WordPress website

January 11, 2010 13 comments

    This tutorial (like most of the others found here) assumes you are running your WordPress site on a Linux/Apache configuration, and you have direct access to your .htaccess file. This article will teach you how to compress all the JavaScript, CSS, PHP, HTML for your WordPress site, which should result in a faster site with less burden on your server (especially if you use shared hosting).

    Note that these techniques are a compendium of advice found on various websites such as

    First you should go to http://www.websiteoptimization.com/services/analyze/ and check the results for your website or blog. You should see .js, .css, .php and .html files are all being transmitted as full-size by the server. You might also want to check ismyblogworking.com for more compression stats.

1. Compress JavaScript

    To compress the JavaScript on a site-wide level, you’ll need to create a PHP file called compress_js.php (really it could be called anything, but we want an obvious name). Put it in your root folder (although technically it could be placed anywhere). Here are the contents of compress_js.php:

<?php
ob_start ("ob_gzhandler");
header ("content-type: text/javascript; charset: UTF-8");
header ("cache-control: must-revalidate");
$offset = 60 * 60;
$expire = "Expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT";
header ($expire);
?>

    This starts PHP’s output buffer. It sets an Expires header, so the script will not only be compressed, but also cached for a short period.

Then add the following into your .htaccess file (or create one if needed):

# javascript compression
ForceType application/x-httpd-php
php_value auto_prepend_file http://www.yoursite.com/compress_js.php

    This tells the server that any JavaScript files should be processed like PHP files, with compress_js.php (our super-duper compression/cache code from above) pre-pended to each PHP file. This is site-wide, so ALL JavaScript files (including ones from your theme and any plugins) will be passed through the script!

    Now go back to http://www.websiteoptimization.com/services/analyze/ and check the results. Any .js files should now show as compressed.

Congratulations! On to CSS compression.

2. Compress CSS

    This one is a bit tougher, because the CSS files must be in their own folder with no other files. Generally this would be a subfolder of your theme or a plugin. Some plugin authors do not use CSS subfolders, making this a tough hack! Once you do it a couple of times, however, it will get easier.

    If the CSS file(s) you want to compress are not in their own folder, create a subfolder called css and put it/them there. You may want to disable the plugin you’re working on to do this. If you’re doing it to WordPress, a plugin like Maintenance Mode should be used so that visitors don’t see any weirdness while you’re moving css files around.

    This is a plugin hack, so unfortunately you’ll need to repeat this process every time you update the plugin (unless you update manually). Fortunately it only takes a few moments to do this. I encourage anyone reading this to write to their favorite plugin developer and ask them to abstract out their CSS (if any) to a subfolder, to make this process easier. Even better, ask them to include the .htaccess and compress_css.php files with their plugin! Let’s start a “Compression Now!” Movement and encourage smarter development.

    Create a file called compress_css.php and put it in the css subfolder (the one you probably just created). Here’s what the file should contain:

<?php
ob_start ("ob_gzhandler");
header ("content-type: text/css; charset: UTF-8");
header ("cache-control: must-revalidate");
$offset = 60 * 60;
$expire = "Expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT";
header ($expire);
?>

    This does the same thing as we did with JavaScript, except the content type is ‘css’ instead of ‘javascript’, to serve css files properly. Create a .htaccess file and put it into the css subfolder. Then add the following into the .htaccess file:

# css compression
AddHandler application/x-httpd-php .css
php_value auto_prepend_file http://path/to/your/compress_css.php

    This pre-pends compress_css.php (from the root folder, where you placed it earlier) to each CSS file in the same folder, which will compress and cache the CSS files in the current folder.

    You’ll then have to manually edit the plugin’s PHP file(s) and ‘point’ it to the new location for the CSS file(s). All of the plugins I’ve seen so far have only one place where the CSS file location is defined. After that you should move the css file(s) into the subfolder. You’re done!

    You’ll need to repeat this process for every plugin or folder that has CSS you want to optimize.

  1. Create css subfolder (if needed)
  2. Create .htaccess file in css subfolder (and make sure compress_css.php path matches the path in .htaccess)
  3. Edit PHP file(s) to point to css subfolder
  4. Move css file(s) to subfolder

    The wp-admin/css folder is a perfect candidate to test out this technique, since it contains only CSS files. You won’t need to edit any PHP to practice on this folder.

    Check http://www.websiteoptimization.com/services/analyze/ again. Your .js AND .css files should now show as compressed. Excellent!

3. Compress PHP

    A lot of “WordPress speed” websites tell you to use mod_deflate to compress your server output. The problem is, what if your web host doesn’t allow it? mod_deflate uses more CPU, so you can see why some web hosts don’t want to enable it. But you can still compress your PHP output, uzing zlib. As a last resort, we can use the technique above. First you do want to check if it’s enabled.

    Your web host may have an option to check php version info, installed modules, etc. If not, you’ll need to do it by hand.

    Start with an empty text file and place the following:

<?php phpinfo(); ?>

    Save it as test.php, upload to your site and load it in your browser. Search the resulting page for the keyword “zlib” and look for “zlib.output_compression”. If it’s “On”, we’re in business. Place the following in your root .htaccess file:

# php compression
php_flag zlib.output_compression On
php_value zlib.output_compression_level number

where “number” is a number from 1 to 9. You’ll need to experiment to see what value works for your site.

    If you can’t use zlib, see below for how we can adapt the above technique for compressing PHP.

4. Compress HTML

    Create the following file in your root folder and call it compress_html.php:

<?php
ob_start ("ob_gzhandler");
header ("content-type: text/html; charset: UTF-8");
header ("cache-control: must-revalidate");
$offset = 60 * 60;
$expire = "Expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT";
header ($expire);
?>

    And put the following into your root .htaccess file:

# html compression
ForceType application/x-httpd-php
php_value auto_prepend_file http://path/to/your/compress_html.php

    As above, this passes all .htm and .html files through the PHP script, which compresses and caches it.

    If you want to include PHP files (for example, your web host doesn’t allow zlib compression), edit .htaccess and add the PHP file-type to the regex as follows:

Change

<FilesMatch "\.(htm|html)">

to

<FilesMatch "\.(htm|html|php)">

since the Content-Type for PHP is also text/html, this is a simple addition that makes a big difference and is so easy to do.

    If you check http://www.websiteoptimization.com/services/analyze/ again, you should see that ALL your files are now compressed. If any CSS files are uncompressed, go back and apply the CSS technique above on the given folder. If little to nothing is compressed, get a better website host! Contact me privately and I’ll send you a link to a good host (I can’t post the link on wordpress.com).

5. Use WP-Super Cache plugin

This plugin is a must for any WP site with even moderate traffic. I started using it after my website started getting throttled by my webhost for repeated hits. My goal was to limit the amount of duplicate requests (especially the database calls). If you do nothing else, this will lower the amount of database calls your site has to make, resulting in a faster site and better browsing experience.

Categories: Hacks Tags: , , , , , ,

Coming soon: Everything WordPress

January 4, 2010 Leave a comment

Welcome to my new blog. This site will feature articles on SEO, WordPress tips, tricks, and PHP hacks. Everything will be from a WordPress perspective, since that’s what I use for my sites and that is what I am most familiar with. The first “real” article will be about compressing your site to make it faster. We’ll review low-level methods for compressing PHP, HTML, CSS and JavaScript using PHP and .htaccess. Comments and questions are welcome, the more the merrier. Stay tuned!

Categories: WordPress Tags: , , , , ,