How to display custom post types on your WordPress blog homepage

How to display custom post types on your WordPress blog homepage

The following code have to be pasted in your functions.php file. Once the file will be saved, it will work.
As you can see in the code, the post, page, album, movie, quote, and attachment types will be displayed. Modify that line to fit your own needs.

add_filter( 'pre_get_posts', 'my_get_posts' );

function my_get_posts( $query ) {
	if ( is_home() )
		$query->set( 'post_type', array( 'post', 'page', 'album', 'movie', 'quote', 'attachment' ) );

	return $query;

Please note that custom post types are not available by default on WordPress 2.9. You could have a look there if you’re looking to implement that functionnality right now.

Credits goes to Justin Tadlock for this handy recipe!

By the way, if you’re looking to advertise on WpRecipes, I got a free spot so be quick! Click here to buy.

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

How to display custom post types on your WordPress blog homepage

WordPress trick: Change theme programatically

WordPress trick: Change theme programatically

The first thing you have to do is to paste the following function in your functions.php file.

function switchTheme($theme) {
    global $wpdb;
    if (isset($theme)) {
        $queries = array("UPDATE wp_options SET option_value = 'default' WHERE option_name = 'template';", "UPDATE wp_options SET option_value = 'default' WHERE option_name = 'stylesheet';", "UPDATE wp_options SET option_value = 'default' WHERE option_name = 'current_theme';");
        foreach ($queries as $query){

What I’ve done in the function was simply to update the wp_options table (change the prefix if necessary) with a new theme name. You probably noticied that I used queries in a loop, which isn’t a good practice. There’s for sure a better way to do it but since I’m not a SQL expert I can’t get anything better. If you know how to achieve the same effect without using looped queries, don’t hesitate to leave me a comment!

Once you’ve pasted the function in your functions.php file, you can call it, for example using a filter. The $theme parameter is the theme name. For example default to restore the good old Kubrick theme.

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress trick: Change theme programatically

WordPress tip: Create a PDF viewer shortcode

WordPress tip: Create a PDF viewer shortcode

The first step is to paste the following code into your functions.php file:

function pdflink($attr, $content) {
	return '<a class="pdf" href="' . $attr['href'] . '">'.$content.'</a>';
add_shortcode('pdf', 'pdflink');

Once you saved the file, you’ll be able to use the shortcode on your posts and page. Here is the syntax:

[pdf href=""]View PDF[/pdf]

Thanks to Noscope for this great shortcode!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress tip: Create a PDF viewer shortcode

Getting started with CouchDB: a beginner’s guide

Getting started with CouchDB: a beginner’s guide

Getting started with CouchDB

Apache CouchDB is one of a new breed of database management systems. These new systems are known as NoSQL. NoSQL is a buzz word term first popularized in early 2009 to describe a database that is non-SQL… NoSQL is a term for a loosely defined class of non-relational data stores that break with a long history of relational databases and ACID guarantees. Data stores that fall under this term may not require fixed table schemas.

The first reason I am quickly growing to love CouchDB, and hence decided to write this post is due to the fact that it is a document-oriented DB, rather then storing content into set tables, it allows us to store information, in a manor that is as flexible as an array.

For example here’s a sample document:

FirstName="Bob", Address="5 Oak St.", Hobby="sailing".

However another document could have this data:

FirstName="Jonathan", Address="15 Wanamassa Point Road", Children=("Michael,10", "Jennifer,8", "Samantha,5", "Elena,2").

This is great because first of all, we are not wasting storage on empty, or null fields.

The second reason this is nice, is that we no longer worry about tables, and columns! we need to set info, then we set just what we need. This CAN cause issues if you do not plan correctly, but we will get into that a little later on.

Another big reason I like CouchDB, is that access is through a REST API, for those who know what that means, this is big! For those who don’t, it means access to get or set data can be granted directly from the browser via javascript, without the need to write extra PHP code on the server side!

Using CouchDB

Now that I have you all hyped about it, lets get to using it. The first thing you need to know is that PHP does not have any built in functions to access a CouchDB database.

/> To do this I recommend PHPillow, a class written by Kore Nordmann. It is definitely one of the best I have seen so far. The second thing you need to know is that setting, and querying a CouchDB is not the same as a MySQL query. As I stated, PHPillow is the best (in my opinion) way to access CouchDB, so that is what I will be using in this example…

Database connection

/> To connect to your CouchDB instance simply use the phpillowConnection class like shown here:

phpillowConnection->createInstance('localhost', 5984, 'user', 'password');

Once created this connection will be used in your document and view classes automatically.

Define a custom document

/> All documents extend the abstract base class phpillowDocument. A complete model defining a blog entry could look like:

class myBlogDocument extends phpillowDocument
    protected static $type = 'blog_entry';

    protected $requiredProperties = array(

    public function __construct()
        $this->properties = array(
            'title'     => new phpillowStringValidator(),
            'text'      => new phpillowTextValidator(),
            'comments'  => new phpillowDocumentArrayValidator(


    protected function generateId()
        return $this->stringToId( $this->storage->title );

    protected function getType()
        return self::$type;

The static property $type defines the type of the stored document and should be unique for each document in your application. If you are implementing a module, prefix this type with the name of the module, like “blog” in this example. If you happen to use a PHP version prior 5.3 you have to return the document type in each of your document classes like shown above. 5.3 and above users can use a more generic approach with returning static::$type in a base document class.

The $requiredProperties array defined the properties, which are mandatory to be set. The properties itself are defined in the $properties property, which is initialized in the constructor of the document. We associate a validator with each property which validates the input set on the document. There are quite complex validators, like the phpillowDocumentArrayValidator shown here, which will be described later, which are all documented in the generated API documentation.

The last thing you need to define is the generation of the document ID. An ID in CouchDB needs to fulfill some requirements, which are ensured by using the protected method stringToId(). Normally you use one somehow unique property of the document. If this is not entirely unique the document handler will append something, so that it will get unique. Just return null if you want CouchDB to give you an unique id for the document.

Using a document

/> Now to save data using the document layout that the above code would create we can simply call:

$doc = new myBlogDocument();
$doc->title = 'New blog post';
$doc->text  = 'Hello world.';

With the call to the save() method the document will be generated and stored in the database. After this a new magic property is available for the document:


Using documents directly this ID is the way to fetch the document back from the database, like:

$doc = new myBlogDocument();

This call retrieved the above document back from the database. The magic CouchDB properties _id and _rev (for revision) are set for the document. Beside the defined properties another property has been created by the wrapper, called revisions, which contains all old (and the current) revisions of the document:

echo $doc->revisions[0]['title'];

If you now change a property on the object and store it again in the database the old revision will also be stored in the database, so that no information is lost on change. This behavior may be deactivated by setting the $versioned property to false.

Did you say revisions?

/> Why yes I did! Thanks for noticing! My Steve Jobs “One more thing!” moment, is that if you alter a document in a CouchDB database, it save the pervious version as a revision automagicly! No need for multiple database entries to make sure your application can roll back!

So thats about it for this tutorial. Next time we will get into how to run more advanced queries using PHPillow.

10 ways to make Internet Explorer act like a modern browser

10 ways to make Internet Explorer act like a modern browser

Enable HTML5 on IE

Ever heard about HTML5? If you’re interested in web development, there’s no doubt about it. For those who doesn’t know, HTML5 is the next major revision of HTM; the core markup language of the World Wide Web.

/> Most modern browser can already handle, at least partially, the new HTML5 recommendations. But as Internet Explorer isn’t well known for its sense of innovation, it will simply ignore the markup.

The html5.js is a very interesting project which aim to make Internet Explorer HTML5 compatible. The only thing you have to do is to embed the html5.js script in your html document header. You can hotlink the script, as shown in the example below:

<!--[if IE]>
<script src=""></script>

» Source :

Use the text-shadow CSS property on IE

Due to the recent implementation of the text-shadow CSS property in Firefox 3.5, designers started to use it quite intensively. Today, most modern browsers can render this property pretty well, but once again, IE ignores it.

/> Happilly, the proprietary, IE-only filter property can imitate text-shadow quite well. The example above shows how to apply the text-shadow property to modern browsers and filter to IE. Note that due to the fact filter isn’t a standard CSS property, it should be isolated using conditional comments.

If you’d like to learn more about the text-shadow property, don’t forget to check out our list of resources to get the most out of the text-shadow property.

p.shadowed {
  text-shadow: #0000ff 0px 0px 3px; /* Modern browsers */
  filter: glow(color=#0000ff,strength=3); /* IE */

» Source :

CSS box-shadow on IE

In my opinion, box-shadow is one of coolest new CSS3 properties, because it allows you to easily create beautiful shadows on any kind of html element, without using any images. A real achievement for designers and front-end web developers!

    box-shadow: 10px 10px 5px #888;

But, don’t ask if Internet Explorer can handle box-shadow. It can’t.

/> Once again, to imitate the box-shadow CSS property, we’ll have to use the filter proprietary property, as shown in the following example:

.shadowed {
        progid:DXImageTransform.Microsoft.DropShadow(color=#969696, offx=1, offy=1)
        progid:DXImageTransform.Microsoft.DropShadow(color=#C2C2C2, offx=1, offy=1)
        progid:DXImageTransform.Microsoft.DropShadow(color=#EFEFEF, offx=1, offy=1);

» Source :

Rounded corners!

Ah, rounded corners. They are so popular with their “Web 2.0? look and feel. The CSS3 specification understood it, and created a property, named border-radius, which is designed to easily create rounded corners without using a single image.

/> For those who doesn’t know, here’s how to use border-radius:


Fortunately, there’s several ways to create IE-compliant rounded corners without using images. My favorite is DD roundies, a small piece of javascript that can round any kind of HTML element.

/> The following example will create rounded corners on any HTML element with the roundify class.

<script type="text/javascript" src="DD_roundies.js"></script>
<script type="text/javascript">
  DD_roundies.addRule('.roundify', '10px');

» Source :

Multi column layouts

CSS3 allows you to automatically display some content in columns. This is a great thing as it give designers a lot more possibilities to create awesome layouts.

/> The following CSS will work on Firefox and Safari. It will automatically add columns to a div element.

.column {
    -moz-column-width: 13em;
    -webkit-column-width: 13em;
    -moz-column-gap: 1em;
    -webkit-column-gap: 1em;

Unfortunately, there’s no way to do something similar on Internet Explorer. But jQuery and its columnize plugin are here to help! The following example shows how easy it is to create columns using jQuery and columnize:

$('#myotherdiv').columnize({ width: 200 });
$('#mythirddiv').columnize({ columns: 2 });

» Source :

CSS3 pseudo-selector emulation

CSS3 introduces lots of extremely useful selectors. Among others, the :nth-child() pseudo-class targets an element that has a certain number of siblings before itself in the document tree, as shown below:

p:nth-child(3) {

As you can guess, these kind of things are way too advanced for IE. To overcome this problem, Keith Clark created a very useful script named ie-css3.js.

/> Using it is easy: Download Robert Nyman’s DOMAssistant, Keith’sie-css3.js and link them in your HTML document header.

<script type="text/javascript" src="DOMAssistantCompressed-2.7.4.js"></script>
<script type="text/javascript" src="ie-css3.js"></script>

» Source :


Opacity is another CSS3 that IE can’t render. It’s such a pity because being allowed to interact on the opacity of a particular element is very interesting in terms of web design.

/> Again, the crappy filter property can help us to achieve a satisfying result on IE. The example below shows how to use filter to make an element transparent.

    opacity:.7; /* Standard CSS */
    filter:alpha(opacity=70); /* IE patch */

Rotating HTML elements

Rotating elements is possible with CSS3, using the transform property.

transform: rotate(240deg);
-webkit-transform: rotate(240deg);
-moz-transform: rotate(240deg);

Internet Explorer will simply ignore all of the 3 declarations above. But hey, IE users got filter, don’t they? Sure, this property isn’t W3C valid, but since it’s Internet Explorer, you shouldn’t ask too much. The following code will imitate transform on all versions of IE:

filter:progid:DXImageTransform.Microsoft.Matrix(M11=0.86602540, M12=0.50000000, M21=-0.50000000, M22=0.86602540);

» Source :

RGBa support

The “a” in RGBa stands for alpha. This new feature allows developers to specify an opacity value for a color, which is extremely useful when coding a website.

 .color-block {
    width: 50%;
    background-color: rgba(0, 0, 255, 0.2); /* Modern browsers */

As usual, Internet Explorer shows its lack of innovation and its inferiority to other browsers with no RGBa support at all. Fortunately, filter can achieve a quite similar effect to RGBa:

<!--[if IE]>
<style type="text/css">
.color-block {
    filter:progid:DXImageTransform.Microsoft.gradient( startColorstr=#99000050,endColorstr=#99000050);
    zoom: 1;

» Source :

IE compliant font embedding

For the past 15 years, the web has been dominated by a few fonts such as Arial, Verdana, Courier and most notably Times New Roman. Those fonts are labeled “web safe”, which means that almost any computer has them installed. (By the way, they aren’t installed on GNU/Linux because they’re not free)

/> But for a year or two, font embedding has become a very interesting and loved technique: It allows you to embed a particular font in your design so your users will see it, nevermind if they have the font installed or not.

Among other techniques, the @font-face method is probably the most clean. Believe it or not, IE has been supporting font embedding since version…4! This is a good thing, but since Microsoft can’t do anything like the others, your font has to be on the proprietary eot format and you have to use a different declaration to embed it on your web pages, as shown below.

Note that if you need to convert a font in Microsoft’s eot format, you can use this free online tool.

@font-face {
    font-family: " your FontName ";
        src: url( /location/of/font/FontFileName.eot ); /* IE */
        src: local(" real FontName "), url( /location/of/font/FontFileName.ttf ) format("truetype"); /* non-IE */

/* THEN use like you would any other font */
.element {
    font-family:" your FontName ", verdana, helvetica, sans-serif;

How to easily monitor your web server using PHP

How to easily monitor your web server using PHP


Maybe I’m stating the obvious, but the PHP script has to be on a different server than the one used for the website you’d like to monitor. If the script is hosted on the same server as your site, then it becomes pretty useless: In fact, if your server is down the script will not be able to run and will not let you know.
The best solution is of course a dedicated server, but a home server can be ok as well. Shared web hosting like those provided by Hostgator or WpWebHost have a low price, but most don’t allow you to set up cron jobs, so be careful if you plan to buy.

The last part of this tutorial will show you how to get sms alerts using Gmail. Please note that depending on your location and cellular phone provider, this part of the tutorial may not work.

1. Creating the monitoring script

The first part of this tutorial is to create the monitor script. Pick up your favorite text editor and create a file named monitor.php. The script is very simple: we only need two functions, one to test if a specific site is available, and the other to alert you by sending an email.

Paste the following in your monitor.php file:

function check($host, $find) {
    $fp = fsockopen($host, 80, $errno, $errstr, 10);
    if (!$fp) {
        echo "$errstr ($errno)\n";
    } else {
       $header = "GET / HTTP/1.1\r\n";
       $header .= "Host: $host\r\n";
       $header .= "Connection: close\r\n\r\n";
       fputs($fp, $header);
       while (!feof($fp)) {
           $str .= fgets($fp, 1024);
       return (strpos($str, $find) !== false);

function alert($host) {
    mail('[email protected]', 'Monitoring', $host.' down');

$host = '';
$find = 'Cats Who Code';
if (!check($host, $find)) alert($host);

The first function we created here, check(), takes two parameters: The first is the server you’d like to check availability (for example, and the second parameter is to find some text on the webpage. This second parameter is an additional security: In fact, by checking if a specific word is contained on the site homepage, we ensure that the site content hasn’t been modified, for example, after a hacking.

If the server isn’t available or if the text to find hasn’t been found, the alert() function is executed, and will send an email to the account of your choice.

Save the monitor.php file and upload it to your monitoring server.

2. Defining a cron job

At this point of the tutorial, we have a working monitoring script, but we have to type in a web browser to check our website, which makes our script almost useless.
The solution to that problem is to create a cron task to make the server execute monitor.php every hour. Open a SSH console to your monitor server and type the following:

0 * * * * /usr/local/bin/php -q /htdocs/www/monitor.php

If your PHP scripts do not have executable permissions, 644 or -rw-r–r– for example, then as part of the command portion of the cron line, you must specify the php interpreter and pass it the filename of the PHP script (including full path to the script from your home directory) that you want executed.

3. Setting up SMS alerts

Right now, we have a working monitoring PHP script, as well as a cron job that will execute the script every hour. If a problem happens, you’ll receive an email.
Due to the popularity of iPhones, Blackberries and other SmartPhones, a lot of people are able to receive emails everywhere they are. Though, some are still using cell phones with no email capability. In this optional step of the tutorial, let’s see how we can easily receive alerts by sms.

Doing so is quite easy. First you have to use Gmail. As it is a free service, you can create a dedicated account for your monitoring alerts. Once finished, login to your account and click on the “Settings” link located on the top right side of the browser window.
Then, select “Forwarding and POP/IMAP”:

As shown in the previous screenshot, the only thing you have to do is to check “Forward a copy of incomming mail” and fill the field with your phone number @ your provider service.
For example, If your phone provider is AT&T, you’ll have to type [email protected].

Have you checked out the highly recommended Digging into WordPress book by Chris Coyier and Jeff Starr?

How to easily monitor your web server using PHP

10+ useful online code editors

10+ useful online code editors

Amy Editor

Created in 2007 by Petr Krontorád, Amy Editor is an advanced editor with a look and feel of a Mac. Amy Editor features lots of useful options, such as line numbers, syntax highlighting, snippets for more than 20 languages, collaboration, and more.
Amy can edit, save and export files. It can also manage projects.



As you can guess, JSBin is an online text editor primarily focused on Javascript. I really love the clean and simple interface. Each code can be tested using a powerful “Preview” feature, and then exported into a text file.
Another good thing to note is that JSBin can import popular Javascript frameworks such as jQuery or Mootools, so you can test your js plugins as well.



Using HTML5 quite intensively, Bespin is a new project from Mozilla Labs. This online editor is very powerful and has lots of cool options. In order to use Bespin, you have to create an account. Note that Bespin can be downloaded and then embedded in any kind of web project, only by adding two files in your header!



Kodingen is another great online editor, probably one of the most powerful tool on this whole list. It can be used unregistered or you can create an account to use advanced functions as such as SVN repositories, collaborative work, etc.
This editor features templates for most programming languages, syntax highlighting, line numbering and more. A must!



Unlike the first few editors featured in this post, EditPad is simple and minimal. No syntax highlighting, no project management…Just a plain page to type your text without any distractions. I’m not a big fan, but this “online notepad” can be a life saver on a particularly slow machine.



TypeIt isn’t a code editor and I hesitated to feature it in this post. This handy tool helps you to access special characters such as French accents, like a visual keyboard does. Definitely a site to have in your bookmarks if you’re often working on multi-language sites.



PractiCode is a very basic code editor. It has very limited functions (Handles CSS, HTML and VbScript) but it is perfect to make quick and dirty code.



9ne (Pronounced Nine) is a nice online text editor, based on the well known GNU Emacs. 9ne provides most of the basic Emacs functionalities and currently supports XML and Javascript syntax highlighting modes.



Vi has always been one of my favorite text editors of all times. Why? Because it is powerful, fast, and you’ll find it everywhere: GNU/linux distros, Mac, web servers… Now, you’ll also find Vi online with this implementation called JSVI. Most Vi functions have been implemented into this web-based version.



As the name says, HTMLedit is a (very basic) HTML editor that can be used for quick and dirty coding. However, its interest is limited, particularly if compared to most other items from this list.



Have you ever felt distracted when working on a buggy piece of code? If yes, there’s no doubt that you will enjoy DarkCopy. This simple online text editor has limited functions but it provides a dark, clutter-free environment so you can concentrate on the most important: getting things done.


SimpleText may have a cool retro Apple look, but it is also a powerful tool that allows you to create, edit, and save plain text files in your web browser. Another good point of SimpleText is that you can host it yourself if you want, using Google Apps Engine. This guide will show you how to do.


Have you checked out the highly recommended Digging into WordPress book by Chris Coyier and Jeff Starr?

10+ useful online code editors

WordPress : 10+ life saving SQL queries

WordPress : 10+ life saving SQL queries

How to execute SQL queries

For those who don’t know yet, SQL queries have to be executed within the MySQL command line interpreter or a web interface such as the popular PhpMyAdmin. Since we’re going to work on WordPress, you should note that the SQL Executionner plugin provides an easy-to-use interface that allows you to run SQL queries directly on your WordPress blog dashboard.

Although all the queries from this article have been tested, don’t forget that you shouldn’t test any of those on a production blog. Also, make sure that you always have a working database backup.

Manually change your password

It may sound like the thing that only happens to others but forgetting a password can happen to any of us. In case you lost your blog admin password, the only solution is to create a new one directly in your MySQL database.
The following query will do it. Notice that we use the MD5() MySQL function to turn our password into an MD5 hash.

UPDATE 'wp_users' SET 'user_pass' = MD5('PASSWORD') WHERE 'user_login' ='admin' LIMIT 1;

Source :

Transfer posts from one user to another

Most WordPress newcomers tend to use the good old “admin” account instead of creating an account with their real name. If you made that mistake and created another account later, you can easily transfer your old “admin” posts to your new account with the SQL query below.
You’ll need the user id of both your old and new accounts.

UPDATE wp_posts SET post_author=NEW_AUTHOR_ID WHERE post_author=OLD_AUTHOR_ID;

Source :

Delete post revisions and meta associated to those revisions

Post revisions are very useful, especially in the case of a multi author blog. However, the problem of post revisions is definitely the number of database records it creates. For exemple, if your blog has 100 posts, which has 10 revisions each, you’ll end up with 1000 records in the wp_posts tables, while only 100 of them are necessary.
Executing this query will delete all post revisions as well as all meta info (custom fields, etc) associated to it. The whole process will result in a consequent gain of database space.

DELETE a,b,c FROM wp_posts a WHERE a.post_type = 'revision' LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id) LEFT JOIN wp_postmeta c ON (a.ID = c.post_id);

Source :

Batch delete spam comments

Imagine that you’re coming back from holidays, where you haven’t had any access to the Internet. If you haven’t installed Akismet and depending on your blog popularity, you may end up with 1000, 2000 or even 10,000 comments to moderate.
You can spend a whole day to moderate the lot, or you can use this life-saving query to delete all unapproved comments. And for your next holidays, don’t forget to install Akismet!

DELETE from wp_comments WHERE comment_approved = '0';

Source :

Find unused tags

Tags are recorded on the wp_terms table. If for some reason a tag has been created but is not used anymore, it stays in the table. This query will let you know which tags are on the wp_terms table without being used anywhere on your blog. You can delete those safely.

SELECT * From wp_terms wt INNER JOIN wp_term_taxonomy wtt ON wt.term_id=wtt.term_id WHERE wtt.taxonomy='post_tag' AND wtt.count=0;

Source :

Find and replace data

This tip isn’t specific to WordPress and is a must know for anyone who’s working with MySQL databases. The MySQL function replace() lets you specify a field name, a string to find, and a replacement string. Once the query is executed, all occurrences of the string to replace will be replaced by the replacement string.
In case of a WordPress blog, this can be useful to batch replace a typo (For example people who repeatedly call the software WordPress…) or an email address.

UPDATE table_name SET field_name = replace( field_name, 'string_to_find', 'string_to_replace' ) ;

Source :

Get a list of your commentators emails

Have you ever received unsolicited emails from blogs you previously commented? I’m sure you did, just like me. The fact is that getting a list of emails from your commentators is extremely easy using the following query. The DISTINCT parameter will make sure that we’ll only get each email once, even if the user commented more than once.
Please note that this is only a proof of concept: Don’t send your users unwanted emails.

SELECT DISTINCT comment_author_email FROM wp_comments;

Source :

Disable all your plugins at once

When things go wrong, especially on a production site, you have to be quick. Considering the fact that plugins are often the source of problems, disabling all your plugins in a second can prevent lots of problems.
Just run the following query:

UPDATE wp_options SET option_value = '' WHERE option_name = 'active_plugins';

Source :

Delete all tags

In WordPress, tags are recorded in the wp_terms tables, along with categories and taxonomies. If you wish to remove all tags, you can’t simply empty or delete the wp_terms as you’ll destroy categories at the same time!
If you want to get rid of your tags, run this query. It will remove all tags and relationships between tags and posts, while leaving categories and taxonomies intact.

DELETE a,b,c
	database.prefix_terms AS a
	LEFT JOIN database.prefix_term_taxonomy AS c ON a.term_id = c.term_id
	LEFT JOIN database.prefix_term_relationships AS b ON b.term_taxonomy_id = c.term_taxonomy_id
	c.taxonomy = 'post_tag' AND
	c.count = 0

Source :

List unused post meta

Post meta is created by plugins and custom fields. They are extremely useful, but they can quickly make your database grow in size. The following query will show you all the records in the postmeta table that doesn’t have corresponding records in the post table.

SELECT * FROM wp_postmeta pm LEFT JOIN wp_posts wp ON wp.ID = pm.post_id WHERE wp.ID IS NULL;

Source :

Disable comments on older posts

Everyone who has been in blogging for more than one year will know: Even after some months, your old posts still receive interest from the public and lots of comments, mostly because they are indexed by search engines. This is a good thing of course, but the problem is for people like me who own technical blogs and have to answer lots of questions related to their old (and sometimes obsolete) posts.
The solution to this problem is to automatically close comments on posts which are too old. This SQL query will close comments on all posts published before January 1, 2009.

UPDATE wp_posts SET comment_status = 'closed' WHERE post_date < '2009-01-01' AND post_status = 'publish';

Source :

Replace commentator url

Previously in this article, I talked about the very useful replace() MySQL function. Here is a good example of how useful it is : Let’s say you previously own a site and used its url in your comments to generate backlinks to this site.
If you sell the site, you can easily replace the old url by your new site url. Simply run this query and you’ll be done!

UPDATE wp_comments SET comment_author_url = REPLACE( comment_author_url, '', '' );

Source :

Replace commentator email adress

Another good example of the replace() function. This query will replace the email adress provided in the comments field, by a new one.

UPDATE wp_comments SET comment_author_email = REPLACE( comment_author_email, '[email protected]', '[email protected]' );

Source :

Delete all comments with a specific url

Lately, I’ve noticied that some clever spammers left some quite relevant comments, but with a link pointing to a viagra site. Unfortunely, when I noticied it the commentator already left lots of comments. The following query will delete all comments with a specific url. The “%” signs means that any url containing the string within the % signs will be deleted.

DELETE from wp_comments WHERE comment_author_url LIKE "%wpbeginner%" ;

Source :

Have you checked out the highly recommended Digging into WordPress book by Chris Coyier and Jeff Starr?

WordPress : 10+ life saving SQL queries

10+ useful code snippets to develop iPhone friendly websites

10+ useful code snippets to develop iPhone friendly websites

Detect iPhones and iPods using Javascript

When developing for the iPhone and the iPod Touch, the first thing we have to do is obviously detect it, so we can apply specific code or styles to it. The following code snippets will detect iPhones and iPods using Javascript, and redirect those users to an iPhone specific page.

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
    if (document.cookie.indexOf("iphone_redirect=false") == -1) {
        window.location = "";


Detect iPhones and iPods using PHP

Although the previous snippet works great, Javascript can be disabled on the iPhone. For this reason, you may prefer to use PHP in order to detect iPhones and iPods touch.

if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod')) {


Set iPhone width as the viewport

How many times did you load a website in your iPhone and it just looked like a thumbnail? The reason of this is that the developer forgot to define the viewport (or didn’t know it existed). The width=device-width statement allows you to define the document width as being the same than the width of the iPhone screen. The two other statements are preventing the page from being scaled, which is useful if you’re developing an iPhone-only website. Otherwise, you can remove those statements.
Defining a viewport is easy: Just insert the following meta in the head section of your html document.

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">


Insert an iPhone specific icon

When a user adds your page to the home screen, the iPhone will automatically use a screenshot of your website as an icon. But you can provide your own icon, which is definitely better.
Defining a custom iPhone icon is easy: Simply paste the following in the head section of your html document. The image should be 57px by 57px in .png format. You do not need to add the shine or corners, as the iPhone will do that for you automatically.

<rel="apple-touch-icon" href="images/template/engage.png"/>


Prevent Safari from adjusting text size on rotate

When you rotate the iPhone, Safari adjust text size. If for some reason you’d like to prevent this effect, simply use the following CSS declaration. It has to be inserted in your CSS file.
The -webkit-text-size-adjust is a webkit-only CSS property that allow you to control text adjustment.

html, body, form, fieldset, p, div, h1, h2, h3, h4, h5, h6 {


Detect iPhone orientation

Due to the fact that the iPhone allow its users to view a page in both portrait and landscape modes, you may need to be able to detect in which mode the document is being read.
This handy javascript function will detect the current iPhone orientation and will apply a specific CSS class so you can style it your way. Note that in this example, the CSS class is added to the page_wrapper ID. Replace it by the desired ID name (See line 24).

window.onload = function initialLoad() {

function updateOrientation(){
    var contentType = "show_";
        case 0:
	contentType += "normal";

	case -90:
	contentType += "right";

	case 90:
	contentType += "left";

	case 180:
	contentType += "flipped";
    document.getElementById("page_wrapper").setAttribute("class", contentType);


Apply CSS styles to iPhones/iPods only

Browser sniffing can be useful, but for many reasons it isn’t the best practice to detect a browser. If you’re looking for a cleaner way to apply CSS styles to the iPhone only, you should use th following. It has to be pasted on your regular CSS file.

@media screen and (max-device-width: 480px){
    /* All iPhone only CSS goes here */


Automatically re-size images for iPhones

On recent websites, most images are above 480 pixels wide. Due to the iPhone small size, there’s a strong chance that images will break out of the wrapper area.
Using the following CSS code, you’ll be able to automatically re-size the website images to 100%. As the device max width is 480px, images will never be wider.

@media screen and (max-device-width: 480px){


Hide toolbar by default

On a small screen such as the iPhone screen, a toolbar is useful but also wastes a lot of space. If you’d like to hide Safari toolbar by default when an iPhone visitor open your website, just implement the following javascript code.

window.addEventListener('load', function() {
    setTimeout(scrollTo, 0, 0, 1);
}, false);


Make use of special links

Do you remember those “mailto” link that were very popular some years ago? This prefix automatically open the default email client used by the person who clicked on it. The iPhone has introduced two similar prefixes, tel and sms, which allows the person who clicked on it to phone or text automatically.
I’m definitely not a fan of those, but maybe that will be useful to you. The only thing you have to do to implement this, is to paste the following anywhere on your html page.

<a href="tel:12345678900">Call me</a>
<a href="sms:12345678900">Send me a text</a>


Simulate :hover pseudo class

As no one is using a mouse on the iPhone, the :hover CSS pseudo class isn’t used. Though, using some Javascript you can simulate the :hover pseudo class when the user will have his finger on a link.

var myLinks = document.getElementsByTagName('a');
for(var i = 0; i < myLinks.length; i++){
   myLinks[i].addEventListener('touchstart', function(){this.className = "hover";}, false);
   myLinks[i].addEventListener('touchend', function(){this.className = "";}, false);

Once you added the code above to your document, you can start css styling:

a:hover, a.hover {
    /* whatever your hover effect is */


Have you checked out the highly recommended Digging into WordPress book by Chris Coyier and Jeff Starr?

10+ useful code snippets to develop iPhone friendly websites

WordPress: How to easily create a Thematic child theme

WordPress: How to easily create a Thematic child theme

What is a Theme framework? And why use it?

Basically, a Theme framework is a WordPress theme that you can extend using functions, styles and child themes.
Child themes are most of the times two files: function.php and style.css. An optional directory containing images can be used as well. Child themes can’t work without a parent theme, which is a synonym for “Theme framework”.

So, why use a Theme framework instead of a “classic” theme? The answer is quite simple: When you need to modify one of WordPress’ functionalities, you don’t edit the core file. Instead, you use a plugin of a hook to modify what you need without editing the core files. That way, you can customize WordPress to fit your needs while at the same time being able to upgrade it without loosing your mods.

Theme frameworks use the same logic: Modify as you need, but don’t edit core file so you’ll be able to upgrade.

In this tutorial, I’m using the Thematic theme framework, a GPL licenced theme brought to you by Ian Stewart. Thematic is in my opinion very powerful and optimized. Therefore, you may be interested in taking a look at other WordPress frameworks as well, such as Hybrid, Headway, Thesis or WP Framework.

Creating the child theme

Right now, you should know what a Theme Framework is and why you should use them. But enough theory for now, let’s get ready to create our own child theme for Thematic.

Download Thematic

Of course, the first thing to do is to download the Thematic Theme Framework. Once finished, unzip the file on your hard drive.

If you want, you can activate Thematic and take a look at your blog. Thematic can be used as a parent theme, or in standalone mode. Without a child theme, Thematic is ready to use and features a really gorgeous typography. There’s no images or even colors, so that you can create your child theme and make Thematic fit your needs, either in its look or functionality.

Create your child theme directory

After you unzipped the Thematic zip file, open the directory. You’ll find a sub directory called thematicsamplechildtheme. Copy it and paste it on the wp-content/themes directory. Rename it with your desired theme name. In this tutorial, I’ll use the name catmatic.

Modify the stylesheet info

Navigate to your new catmatic (or whatever you named it) directory. you’ll find two files: The first is functions.php and the other one is style.css. Open style.css in your favorite text editor. You’ll find the following lines:

Theme Name: A Thematic Child Theme
Theme URI:
Description: Use this theme to start your Thematic Child Theme development.
Author: Ian Stewart
Author URI:
Template: thematic
Version: 1.0
Tags: Thematic
Thematic is © Ian Stewart

What you have to do is simply to name your child theme and give more info about it, as in the following example :

Theme Name: Catmatic
Theme URI:
Description: A Thematic child theme.
Author: Jean-Baptiste Jung
Author URI:
Template: thematic
Version: 1.0
Tags: Thematic
Thematic is © Ian Stewart

Once finished, save the style.css file.

Styling the theme

At this point of the tutorial, we have prepared our child theme but we haven’t started to code yet. So what are we waiting for? The first stage of child theme development is to give the desired look to the Thematic framework, using CSS and images.

Add CSS Styles

Defining CSS styles on your theme child is definitely easy. All you have to do is to add styles to the style.css file from the catmatic directory.

Add images

Adding images to your child theme isn’t hard either. To do so, navigate to wp-content/themes/catmatic and create a new directory named images. (You can name it the way you want, but images is pretty much self-explanatory)

Then, simply put image files in the images directory. If you want to link to those images using CSS, you’ll do the following:

    background: #fff url(images/bg.gif) repeat-x top left;

Supercharging Thematic

Well, after having some CSS fun, your Thematic child theme should look as you want it to. Though, what if you want to modify the theme? Should you edit Thematic theme files?
No, you shouldn’t. Of course, it is possible to do it but it is not a good practice at all. If you’re familiar with WordPress development, you probably know about hooks, which allow you to “hook” a custom function to another. In addition to WordPress hooks, Thematic also adds lots of hooks that allow you to do many things to customize your child theme.

Add functions/hooks

Add your custom functions to your child theme is easier than it seems: Open the functions.php file from your child theme directory and paste your functions there.

To help you get started, here is a bunch of ready-to-use functions:

Modify theme link:

function my_footer($thm_footertext) {
	$thm_footertext = 'Powered by WordPress, theThematic Theme framework and the Catmatic child theme.';
	return $thm_footertext;
add_filter('thematic_footertext', 'my_footer');

Define where to use excerpt/full posts

$full_content = false;
function childtheme_content($content) {
	if ($full_content) {
		$content= 'full';
	} elseif (is_home() || is_front_page()) {
		$content= 'excerpt';
	} elseif (is_single()) {
		$content = 'full';
	} elseif (is_tag()) {
		$content = 'excerpt';
	} elseif (is_search()) {
		$content = 'excerpt';
	} elseif (is_category()) {
		$content = 'excerpt';
	} elseif (is_author()) {
		$content = 'excerpt';
	} elseif (is_archive()) {
		$content = 'excerpt';
	return $content;
add_filter('thematic_content', 'childtheme_content');

Display Thematic menu above header

function remove_thematic_actions() {

Add a favicon

function childtheme_favicon() { ?>
	<link rel="shortcut icon" href="<?php echo bloginfo('stylesheet_directory') ?>/images/favicon.png"/>
<?php }
add_action('wp_head', 'childtheme_favicon');

Activate your theme

Right now, you should have a child theme that fit your needs in both the look and functionality. The last thing we have to do is to upload the theme to your wp-content/themes directory and activate it. Make sure that Thematic is available on your wp-content/themes directory as well.

Have you checked out the highly recommended Digging into WordPress book by Chris Coyier and Jeff Starr?

WordPress: How to easily create a Thematic child theme

10 interesting projects from Google Code

10 interesting projects from Google Code


Do you remember the old days of web development, when IE6 was the king? (ok, it sounds soooo bad now but if you were already building sites in 2002 you know what I’m talking about!) It was extremely easy to force copy to clipboard.
But, for obvious security concerns, Firefox doesn’t allow clipboard access by default. This is a good thing, but for some sites, being able to copy into clipboard is a must.

Using powerful Javascript and a .swf file, ZeroClipboard allow you copy information into the user clipboard. For a live demo, just have a look to my Coupons For Bloggers site.
» Visit ZeroClipboard


As a blogger, I know how important Twitter is to stay tuned with my readers and share my favorite links with them. But as you know, Twitter allows only 140 characters in messages. In order to create shorter urls, you can use a service like or, or you can get yourls, and create your own service.

Yourls is built in PHP and is very easy to configure. If you’re using WordPress, you’ll probably be happy to know that yourls has its own WordPress plugin.
» Visit Yourls


I know I already talked about Minify in a previous article, but I simply cannot resist to spread the word about this very cool piece of code.
Minify is extremely simple to install and will combine, minify, and cache JavaScript and CSS files on demand to speed up page loading.

Installing minify is extremely easy: you just have to upload a directory to your site document root and Minify will start to speed up your blog. Wonderful, isn’t it?
» Visit Minify


Being a WordPress fan, I really love the concept of Theme frameworks. For those who doesn’t know what it is, Theme frameworks are WordPress themes which contain lots of functions and styles. You can extend both in looks and functionality by adding a child theme.
For example, my other blog Cats Who Blog is using the Thesis theme framework that I extended using my own styles and functions.

Many commercial frameworks are availables, but Thematic is 100% free. A definitive must download if you’re into WordPress!
» Visit Thematic


As you may guess, Flexlib is an open source Adobe Flex library. It provides lots of components that you can freely use in your Flex or Air projects.
The currently available components include: AdvancedForm, Base64Image, EnhancedButtonSkin, CanvasButton, ConvertibleTreeList, Draggable Slider, Fire, Highlighter, HorizontalAxisDataSelector IconLoader, ImageMap, PromptingTextArea, PromptingTextInput, Scrollable Menu Controls, SuperTabNavigator, Alternative Scrolling Canvases, Horizontal Accordion, TreeGrid, FlowBox, Docking ToolBar, and Flex Scheduling Framework.
» Visit Flexlib

Zen Coding

As a web developer, I often find it frustrating having to type lots of tags and attributes to reach the desired result. HTML tags are necessary of course, but that doesn’t mean it should consume so much typing.
This may be the idea Sergey Chikuyonok before he started to develop Zen Coding. What is Zen Coding? It is a handy set of tools for high-speed HTML and CSS coding. It integrate in your favorite text editor and then provide functions and shortcuts to speed up your development.

As an example, if you type this:


You’ll get the following output:

<div id="content">

If you want to know more about Zen Coding, Smashing Magazine has a nice article about it.
» Visit Zen Coding


On the internet, design matters. Some people are good for designing, some, like me, aren’t. Happilly, those who aren’t designers (or who are bad designers!!) should take advantage of projects like this one.
Sexybuttons is a small CSS framework that allow you to instantanely create gorgeous buttons for your blog, websites and web apps. If you like CSS buttons, don’t forget to have a look to my Top 10 CSS buttons tutorial list.
» Visit Sexybuttons

jQuery transmit

Who doesn’t like jQuery? This very handy Javascript framework allows developers to enhance both the design and usability of your website. Thanks to plugins, jQuery can be easily enhanced with the functionalities you need. There’s a bunch of very cool jQuery plugins available from Google code so it was very hard to choose one. However, file upload has always been a major problem in web development and this jQuery plugin will be extremely helpful.

Using jQuery transmit is incredibely easy :

$(document).ready(function() {
    var options = {
        allowedFileTypes: [{
            description: "Images",
            extensions: "*.jpg; *.gif; *.png"

    $("#transmit").transmit("", options);

» Visit jQuery Transmit

dompdf : Convert HTML to PDF using PHP

The PDF format is useful for many thing such as invoices, and is largely used in business. dompdf is an advanced HTML to PDF converted which can download and read external stylesheets, inline style tags, and the style attributes of individual HTML elements. It also supports most presentational HTML attributes.
» Visit dompdf


Spam is definitely a big problem for blogs and websites. Although it is still impossible to completely prevent spam, some tools can help you a lot to fight it.
Stop-spam is one of those tools. It is lightweight, compatible with all blogs and forums (WordPress, PhpBB, Movable Type, etc) and easy to install. It automatically blacklists well known domains and IPs used by spammers. Of course, you can edit lists to blacklist/whitelist to add more domains and IPs.
» Visit stop-spam

Any other you’d like to mention? Don’t hesitate to let me know in a comment!

Have you checked out the highly recommended Digging into WordPress book by Chris Coyier and Jeff Starr?

10 interesting projects from Google Code