WordPress tip: Get rid of unused post revisions

WordPress tip: Get rid of unused post revisions

Just run the following query on your WordPress database, and all revisions (As well as meta associated with it) will be deleted from your database.
Of course, do not forget to make a backup of your database before running the code.

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);

If you’d like to see more SQL queries for WordPress, make sure to read this post.

Thanks to One Extra Pixel for this cool query!

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

WordPress tip: Get rid of unused post revisions

WordPress tip: Get rid of unused shortcodes

WordPress tip: Get rid of unused shortcodes

Simply run the following SQL query on your WordPress database, using the command line client or PhpMyAdmin. In this example, I assume the unused shortcode is [tweet].
Don’t forget to backup your database before using this query.

UPDATE wp_post SET post_content = replace(post_content, '[tweet]', '' ) ;

If you like to know more about WordPress SQL queries, you should have a look to this article.

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

WordPress tip: Get rid of unused shortcodes

10 sql tips to speed up your database

10 sql tips to speed up your database

Design your database with caution

This first tip may seems obvious, but the fact is that most database problems come from badly-designed table structure.
For example, I have seen people storing information such as client info and payment info in the same database column. For both the database system and developers who will have to work on it, this is not a good thing.
When creating a database, always put information on various tables, use clear naming standards and make use of primary keys.
Source: http://www.simple-talk.com/sql/database-administration/ten-common-database-design-mistakes/

Know what you should optimize

If you want to optimize a specific query, it is extremely useful to be able to get an in-depth look at the result of a query. Using the EXPLAIN statement, you will get lots of useful info on the result produced by a specific query, as shown in the example below:

EXPLAIN SELECT * FROM ref_table,other_table WHERE ref_table.key_column=other_table.column;

Source: http://dev.mysql.com/doc/refman/5.0/en/using-explain.html

The fastest query… Is the one you don’t send

Each time you’re sending a query to the database, you’re using a bit of your server resources. This is why, on high traffic sites, the best thing you can do in order to speed up your database is to cache queries.

There’s lots of solutions to implement a query cache on your server. Here are a few:

  • AdoDB: AdoDB is a database abstraction library for PHP. It allows you to use the database system of your choice (MySQL, PostGreSQL, Interbase, and way much more) and it is designed for speed. AdoDB provides a simple, yet powerful caching system. And last but not least, AdoDB is licenced under the BSD, which means that you can use freely on your projects. A LGPL licence is also available for commercial projects.
  • Memcached: Memcached is a distributed memory caching system which is often used to speed up dynamic database-driven websites by alleviating database load.
  • CSQL Cache: CSQL Cache is an open-source data caching infrastructure. Never tested it personally, but it seems to be a great tool.

Don’t select what you don’t need

A very common way to get the desired data is to use the * symbol, which will get all fields from the desired table:

SELECT * FROM wp_posts;

Instead, you should definitely select only the desired fields as shown in the example below. On a very small site with, let’s say, one visitor per minute, that wouldn’t make a difference. But on a site such as Cats Who Code, it saves a lot of work for the database.

SELECT title, excerpt, author FROM wp_posts;

Use LIMIT

It’s very common that you need to get only a specific number of records from your database. For example, a blog which is showing ten entries per page. In that case, you should definitely use the LIMIT parameter, which only selects the desired number of records.
Without LIMIT, if your table has 100,000 different records, you’ll extract them all, which is unnecessary work for your server.

SELECT title, excerpt, author FROM wp_posts LIMIT 10;

Avoid queries in loops

When using SQL along with a programming language such as PHP, it can be tempting to use SQL queries inside a loop. But doing so is like hammering your database with queries.
This example illustrates the whole “queries in loops” problem:

foreach ($display_order as $id => $ordinal) {
    $sql = "UPDATE categories SET display_order = $ordinal WHERE id = $id";
    mysql_query($sql);
}

Here is what you should do instead:

UPDATE categories
    SET display_order = CASE id
        WHEN 1 THEN 3
        WHEN 2 THEN 4
        WHEN 3 THEN 5
    END
WHERE id IN (1,2,3)

Source: http://www.karlrixon.co.uk/articles/sql/update-multiple-rows-with-different-values-and-a-single-sql-query/

Use join instead of subqueries

As a programmer, subqueries are something that you can be tempted to use and abuse. Subqueries, as show below, can be very useful:

SELECT a.id,
    (SELECT MAX(created)
    FROM posts
    WHERE author_id = a.id)
AS latest_post FROM authors a

Although subqueries are useful, they often can be replaced by a join, which is definitely faster to execute.

SELECT a.id, MAX(p.created) AS latest_post
FROM authors a
INNER JOIN posts p
    ON (a.id = p.author_id)
GROUP BY a.id

Source: http://20bits.com/articles/10-tips-for-optimizing-mysql-queries-that-dont-suck/

Be careful when using wildcards

Wildcards are very useful because they can substitute for one or more characters when searching for data in a database. I’m not saying that you shouldn’t use them, but instead, you should use them with caution and not use the full wildcard when the prefix or postfix wildcard can do the same job.
In fact, doing a full wildcard search on a million records will certainly kill your database.

#Full wildcard
SELECT * FROM TABLE WHERE COLUMN LIKE '%hello%';
#Postfix wildcard
SELECT * FROM TABLE WHERE COLUMN LIKE  'hello%';
#Prefix wildcard
SELECT * FROM TABLE WHERE COLUMN LIKE  '%hello';

Source: http://hungred.com/useful-information/ways-optimize-sql-queries/

Use UNION instead of OR

The following example use the OR statement to get the result:

SELECT * FROM a, b WHERE a.p = b.q or a.x = b.y;

The UNION statement allows you to combine the result sets of 2 or more select queries. The following example will return the same result that the above query gets, but it will be faster:

SELECT * FROM a, b WHERE a.p = b.q
UNION
SELECT * FROM a, b WHERE a.x = b.y

Source: http://www.bcarter.com/optimsql.htm

Use indexes

Database indexes are similar to those you can find in libraries: They allow the database to find the requested information faster, just like a library index will allow a reader to find what they’re looking for without loosing time.
An Index can be created on a single column or a combination of columns in a database table. A table index is a database structure that arranges the values of one or more columns in a database table in specific order.

The following query will create an index on the Model column from the Product table. The index is called idxModel:

CREATE INDEX idxModel ON Product (Model);

Source: http://www.sql-tutorial.com/sql-indexes-sql-tutorial/

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

10 sql tips to speed up your database

Top 10 best practices for front-end web developers

Top 10 best practices for front-end web developers

Explain which div you’re closing

Most of the time when I’m viewing a website source, I see, at the very bottom of the page, an almost endless list of closing </div> tags. In fact, many beginners think they just have to use divs instead of tables to produce quality code. Divs are cleaners than tables, but without proper code organization, it can be as (or even sometimes more) messy as table based code.

Using indentation is a good start. But a tip that can definitely make you save lot of time is to comment every div tag you’re closing, as shown in the example below:

<div id="header">
  <div id="sub" class="first left">
    ...
  </div><!-- #sub.first.left -->
</div><!-- #header -->

Use a CSS reset

Unless you’re a beginner or if you were on vacation on a desert island for the last 6 years, you might already know how useful a CSS reset it. Because by default, browsers don’t apply the same default styling to HTML elements, a CSS reset will ensure that all element have no particular style so you can define your own without the risk of many cross-browser rendering issues.

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-size: 100%;
	vertical-align: baseline;
	background: transparent;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}

/* remember to define focus styles! */
:focus {
	outline: 0;
}

/* remember to highlight inserts somehow! */
ins {
	text-decoration: none;
}
del {
	text-decoration: line-through;
}

/* tables still need 'cellspacing="0"' in the markup */
table {
	border-collapse: collapse;
	border-spacing: 0;
}

Source: http://meyerweb.com/eric/tools/css/reset/index.html

Don’t use @import

CSS files can be included using the @import directive. This can be useful when, for example, you want to include a stylesheet into another. Another common practice is to include CSS file in html documents using the following:

<style type="text/css>
  @import url('a.css');
  @import url('b.css');
</style>

While it works, the @import directive is much slower than the other way to include stylesheets into a html document:

<link rel='stylesheet' type='text/css' href='a.css'>
<link rel='stylesheet' type='text/css' href='proxy.css'>

It will not make a difference on low traffic websites, but if you have the chance to own a popular website, don’t waste your visitor’s time using @import.
Source: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

“Smush” your images

Being a developer, I always found that optimizing my images for the web wasn’t easy. I tried the good old “Save for web” Photoshop command, but most of the time, I ended up with images that were either too big or without a sufficient quality.
As a result, I had the bad habit of using unoptimized images on my websites. This isn’t a problem when you don’t have to care about your site’s bandwidth, but after my recent switch on my vps.net virtual private server, I had to be careful with image sizes.

At this time, I found a very cool tool named Smush It: You enter your unoptimized image url, and Smush It will create a perfectly optimized image for you. You can save up to 70% of the file size, while keeping the original quality. As an example, all the images from my list of online code editors have been “smushed”.

Don’t mix CSS with HTML

As a markup language, the right use of HTML is to organize documents by defining a header, a footer, lists, blockquotes, etc. Some time ago, front-end web developers often used now deprecated HTML attributes to style a particular element.
Nowadays, the style attribute allows developers to insert CSS directly into a html document. This is very useful for testing or when you’re in a hurry. But the style attribute is bad practice, that goes completely against the CSS philosophy.

The following example illustrates how dirty and hard to read a simple line of code can become, with the style attribute:

<a href="http://www.catswhocode.com" style="background:#069;padding:3px;font-weight:bold;color:#fff;">Cats Who Code</a>

Don’t mix Javascript with HTML

Just like mixing your html code with css is bad practice, you shouldn’t use any Javascript in your html documents. The following bad practice illustrates an onclick event:

<a id="cwc" href="http://www.catswhocode.com" onclick="alert('I love this site!');">Cats Who Code</a>

The same result can be achieved using unobstructed Javascript. In this example, I’m using the popular jQuery framework:

$(document).ready(function() {
  $('#cwc').click(function() {
    alert('I love this website');
  });
});

This may seems a bit harder at first, especially for beginners; but it is definitely not, and it will keep your html document clean.

Use conditional comments

You know it, IE sucks, and some clients suck even more by requiring you to create webpages which are compatible with this obsolete browser. To target specific versions of IE, you can use the well known IE hacks, as shown below:

height: 200px; /* normal browsers */
_height: 300px; /* IE6 */
.height: 250px; /* IE7 */
*height: 350px; /* All IEs */

Those hacks are extremely useful sometimes, but they are not the best way to target a specific version of IE, and it will cause your CSS validation to fail.

Instead, you should use the conditional comment shown below to target IE6.

<link href="style.css" rel="stylesheet" type="text/css" />

<!--[if lte IE 6]>
  <link href="ie.css" rel="stylesheet" type="text/css" />
<![endif]-->

Place Javascript file at the bottom

A popular practice of the late 90’s/early 2000’s was to place Javascript files within the <head> and </head> tags. The problem is that your javascript files will be loaded first, and consequently your content will be loaded after.

By placing Javascript files at the bottom of your documents, you’ll ensure that JS files will be loaded only when the content has been properly displayed.

    ...
    <script type='text/javascript' src='jquery.js?ver=1.3.2'></script>
  </body>
</html>

Use HTML semantically

HTML is not a programming language. It is a markup language, used to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, and more.
If you started to create websites in the good old 90’s or in the beginning of the century, you know how dirty the markup was at the time. But happilly, it has evolved.
Among other things, it is important to use html element semantically. As an example, a navigation menu should always be an unordered list:

<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">About</a></li>
  <li><a href="#">Contact</a></li>
  <li><a href="#">Blog</a></li>
</ul>

Test WHILE you build to avoid cross-browser issues

One of the biggest mistake I ever made when developing html, CSS, and javascript, was not to test my pages on multiple browser while I was writing them. Instead, I used to write all my code and just view in Firefox to see how it was rendered.
In theory, this should be good. But as you know, cross-browser issues are a major problem for front-end developers, especially due to IE. If you test your documents on Firefox/IE/Chrome while your writing it, cross-browser rendering problems will be much easier to fix. I have lost hours not doing it, so I hope this final tip will help you saving your precious time. To test on multiple versions of IE, I use this very handy tool. Happy coding ;)

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

Top 10 best practices for front-end web developers

How to automatically remove the Nofollow from your posts

How to automatically remove the Nofollow from your posts

Copy the following code, and paste it on the functions.php file from your theme. Once you saved the file file, the rel=”nofollow” attributes will be removed.

function remove_nofollow($string) {
	$string = str_ireplace(' rel="nofollow"', '', $string);
	return $string;
}
add_filter('the_content', 'remove_nofollow');

Thanks to Jeff Starr for this awesome piece of code. Have you checked out the book Jeff wrote with Chris Coyier? It’s called Digging into WordPress and it is great!

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

How to automatically remove the Nofollow from your posts

How to automatically use resized images instead of originals

How to automatically use resized images instead of originals

Simply paste the following code on your functions.php file and save it. No other action is needed!

function replace_uploaded_image($image_data) {
    // if there is no large image : return
    if (!isset($image_data['sizes']['large'])) return $image_data;

    // paths to the uploaded image and the large image
    $upload_dir = wp_upload_dir();
    $uploaded_image_location = $upload_dir['basedir'] . '/' .$image_data['file'];
    $large_image_location = $upload_dir['path'] . '/'.$image_data['sizes']['large']['file'];

    // delete the uploaded image
    unlink($uploaded_image_location);

    // rename the large image
    rename($large_image_location,$uploaded_image_location);

    // update image metadata and return them
    $image_data['width'] = $image_data['sizes']['large']['width'];
    $image_data['height'] = $image_data['sizes']['large']['height'];
    unset($image_data['sizes']['large']);

    return $image_data;
}
add_filter('wp_generate_attachment_metadata','replace_uploaded_image');

Thanks to Serge Rauberfor sharing his great tip with us!

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

How to automatically use resized images instead of originals

WordPress tip: Insert posts programmatically

WordPress tip: Insert posts programmatically

Just paste the following code anywhere on WordPress theme files. If you want to test, I recommend pasting it in your functions.php file.
That’s all you have to do. Once executed, this code will insert a new post into WordPress database.

global $user_ID;
$new_post = array(
    'post_title' => 'My New Post',
    'post_content' => 'Lorem ipsum dolor sit amet...',
    'post_status' => 'publish',
    'post_date' => date('Y-m-d H:i:s'),
    'post_author' => $user_ID,
    'post_type' => 'post',
    'post_category' => array(0)
);
$post_id = wp_insert_post($new_post);

Thanks to Matt Harzewski for this great piece of code!

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

WordPress tip: Insert posts programmatically

How to remove “private” and “protected” from the post title

How to remove “private” and “protected” from the post title

The only thing you have to do is to paste the following piece of code in your functions.php file. Once you’ll save the file, the hack will be applied to your your posts.

function the_title_trim($title) {
	$title = attribute_escape($title);
	$findthese = array(
		'#Protected:#',
		'#Private:#'
	);
	$replacewith = array(
		'', // What to replace "Protected:" with
		'' // What to replace "Private:" with
	);
	$title = preg_replace($findthese, $replacewith, $title);
	return $title;
}
add_filter('the_title', 'the_title_trim');

Credits goes to Chris Coyier for this awesome piece of code. Have you checked out the book Chris wrote with Jeff Starr? It’s called Digging into WordPress and it is a must-have for all WordPress fans!

Personal announcement, I’m selling the webdev.fm domain name for only $50. Just send me an email if you want it!

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

How to remove “private” and “protected” from the post title

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){
            $wpdb->query($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="http://docs.google.com/viewer?url=' . $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="http://yoursite.com/linktoyour/file.pdf"]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(
        'title',
        'text',
    );

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

        parent::__construct();
    }

    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.';
$doc->save();

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:

$doc->_id;

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

$doc = new myBlogDocument();
$doc->fetchById('blog_entry-new_blog_post');

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+ 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 = "http://m.espn.go.com/wireless/?iphone&i=COMR";
    }
}

Source: http://davidwalsh.name/detect-iphone

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')) {
    header('Location: http://yoursite.com/iphone');
    exit();
}

Source: http://davidwalsh.name/detect-iphone

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;">

Source: http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

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"/>

Source: http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

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 {
    -webkit-text-size-adjust:none;
}

Source: http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

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() {
    updateOrientation();
}

function updateOrientation(){
    var contentType = "show_";
    switch(window.orientation){
        case 0:
	contentType += "normal";
	break;

	case -90:
	contentType += "right";
	break;

	case 90:
	contentType += "left";
	break;

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

Source: http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

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 */
}

Source: http://csswizardry.com/2010/01/iphone-css-tips-for-building-iphone-websites/

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){
    img{
        max-width:100%;
        height:auto;
    }
}

Source: http://csswizardry.com/2010/01/iphone-css-tips-for-building-iphone-websites/

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);

Source: http://articles.sitepoint.com/article/iphone-development-12-tips/2

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>

Source: http://articles.sitepoint.com/article/iphone-development-12-tips/3

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 */
}

Source: http://www.evotech.net/blog/2008/12/hover-pseudoclass-for-the-iphone/

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: http://themeshaper.com/
Template: thematic
Version: 1.0
Tags: Thematic
.
Thematic is © Ian Stewart http://themeshaper.com/
.
*/

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: http://www.catswhocode.com
Description: A Thematic child theme.
Author: Jean-Baptiste Jung
Author URI: http://www.catswhocode.com
Template: thematic
Version: 1.0
Tags: Thematic
.
Thematic is © Ian Stewart http://themeshaper.com/
.
*/

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:

body{
    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() {
    remove_action('thematic_header','thematic_access',9);
}
add_action('wp','remove_thematic_actions');
add_action('thematic_aboveheader','thematic_access');

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 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="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

» Source : http://remysharp.com/2009/01/07/html5-enabling-script/

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 : http://www.howtocreate.co.uk/textshadow.html

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!

.shadowed{
    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 {
    filter:
        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 : http://ole-laursen.blogspot.com/2009/08/using-css3-box-shadow-with-ie.html

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:

.round{
    border-radius:5px;
    -moz-border-radius:5px;
    -webkit-border-radius:5px;
}

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');
</script>

» Source : http://www.dillerdesign.com/experiment/DD_roundies/

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:

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

» Source : http://welcome.totheinter.net/2008/07/22/multi-column-layout-with-css-and-jquery/

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) {
    color:#069;
}

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 : http://www.keithclark.co.uk/labs/ie-css3/

Opacity

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.

.element{
    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 : http://msdn.microsoft.com/en-us/library/ms533014%28VS.85%29.aspx

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 {
    background:transparent;
    filter:progid:DXImageTransform.Microsoft.gradient( startColorstr=#99000050,endColorstr=#99000050);
    zoom: 1;
}
</style>
<![endif]-->

» Source : http://css-tricks.com/rgba-browser-support/

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;
}