Automatically replace content in PRE tags by HTML Entities

Automatically replace content in PRE tags by HTML Entities

Just paste the following in your functions.php file. Once saved, all your content with <pre> and </pre> tags will be automatically replaced by html entities.

function pre_entities($matches) {
	return str_replace($matches[1],htmlentities($matches[1]),$matches[0]);
}
//to html entities;  assume content is in the "content" variable
$content = preg_replace_callback('/<pre.*?>(.*?)<\/pre>/imsu',pre_entities, $content);

Credits goes to David Walsh for this very cool tip!

By the way, I recently reviewed the new “WpSEO” plugin on CatsWhoBlog so you should definitely take a look!

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

Automatically replace content in PRE tags by HTML Entities

Best WordPress Plugins By Category

Premium WordPress Plugins by category

– Advertising –

  • OIO Publisher – Complete plugin that removes all hassle for bloggers who manage advertising. Automates banners, text links, paid reviews, and collects the money for you. [Full Review]

– Affiliates –

  • Auction Thumbs – Plugin that allows you to easily integrate eBay Partner Network ads into your WordPress Blog. [Full Review]
  • PHP Bay Pro – Premium plugin that integrates eBay auction ads into your WordPress blog. [Full Review]
  • WP Affiliate Pro – Allows you to manage your affiliate links from within your WordPress dashboard. Also allows you to mask links and a number of other features. [Full Review]
  • WP Ninja Affiliate – Similar to WP Affiliate Pro plugin, but provides some additional features including multiple keywords and caching. [Full Review]

– SEO –

  • WP SEO Sniper – Extreme SEO plugin designed to give people conscious of SEO full control over their blogs from the WordPress dashboard. Significant upgrade to the All-in-One SEO Pack plugin. [Full Review]

– Websites –

  • WP Review Site – Simply activate theme and plugin to create a full-featured review website. No additional work needed, allowing you to make a number of these sites quickly! [Full Review]

Free WordPress Plugins

– Admin Tools –

  • Gamer’s Pack – Makes your blog viewable using the Nintendo DS, Nintendo Wii, and PSP gaming systems. [Full Review]
  • GoCodes – Easily create redirects from your WordPress Dashboard that point anywhere. Great for hiding affiliate links. [Full Review]
  • Google Sitemap – Creates a fully-compliant sitemap for search engines. [Full Review]
  • Greet Box – Identifies where traffic is being referred from and displays the appropriate welcome message to them, encouraging to subscribe to your feed, Digg or Stumble your posts, etc. [Full Review]
  • In Series – Allows you to easily group a series of posts into a series. [Full Review]
  • MobilePress – Optimizes your WordPress blog for mobile phones including the popular iPhone. [Full Review]
  • No Self Ping – Prevents your blog from sending pingbacks internally to your other posts. [Full Review]
  • WP-o-Matic – Allows users to collect feeds and auto-generate posts on your blog. [Full Review]
  • WordPress Backup – Plugin that backups up your WordPress themes, WordPress plugins, images, and other non-database stuff. Works with WP-DB Manager. [Full Review]
  • WP-DB Manager – Plugin that gives you full control over your WordPress database backups. Works with the WordPress Backup plugin. [Full Review]
  • WP Sticky – Allows users to feature a post at the top of their homepage for a day or permanently. [Full Review]
  • WP-Super Cache – Creates a cache of your posts to avoid server load. Great for surviving a Digg. [Full Review]

– Advertising –

– Authors –

– Comments –

  • CubePoints – CubePoints allows you to choose a certain amount of points for each comment posted by a certain commentator. You can offer premium content, allow readers to purchase merchandise or maybe even an advertisement for your blog with a certain amount of points. [Full Review]
  • Keyword Luv – Adds an extra field to your comments where people can enter their website so they don’t add their website’s name in the name field for SEO anchor text purposes. [Full Review]
  • Liz Comment Count – Displays a comment count in a similar fashion to the Feedburner feed count widget. [Full Review]
  • MyAvatars – Automatically inserts the commentators MyBlogLog avatar next to their comment using the e-mail address provided. If unavailable, it will attempt to pull the bloggers Gravatar. [Full Review]
  • Show Top Commentators – Allows you to display your top commentators automatically in a place of your choosing. Great for encouraging comments. [Full Review]
  • Smilies Themer – Plugin that offers a variety of smilies styles to place in the comments section of your blog. [Full Review]
  • Subscribe to Comments – Allows readers to receive e-mail notifications when a follow up comment is left. [Full Review]

– Domaining –

  • Domain Name Portfolio – This plugin automatically creates a page in WordPress that domainers can use to display their domain portfolio. Everything is controlled from the dashboard. [Full Review]

– Downloads –

– Feeds –

– Forums –

  • RS Discuss – Plugin that allows you to easily integrate a forum into your existing WordPress blog. [Full Review]

– Maintenance –

– Miscellaneous –

  • Best Posts Summary – Automatically generates a daily, weekly, or monthly review post. Includes both post titles and brief descriptions. [Full Review]
  • BreadCrumb Navigation XT – Allows you to provide your readers with additional blog navigation. [Full Review]
  • Get Firefox Banner – Shows a banner to IE6 and IE7 web browser users recommending they switch to Firefox. Great for blogs whose WordPress theme is optimized for Firefox. [Full Review]
  • Popularity Contest – Monitors your website traffic and gives you reports on your popular posts. Plugin is fully customizable allowing you to set the values used to calculate your posts popularity. [Full Review]
  • WP-eCommerce – Plugin that allows you to create an online shop on your WordPress blog [Full Review]
  • WP-Email – Allows you to add an “Email This!” button to your WordPress blog. [Full Review]
  • WP-Submission – Creates a submission page then places all submissions into a post draft. Ideal for group writing projects. [Full Review]

– Related Posts –

– SEO –

  • All-in-One SEO Pack – The Ultimate SEO WordPress plugin. Allows you to set your homepage meta information and automatically generate custom meta information for your individual posts. [Full Review]
  • Permalink Redirect – Creates a 301 Redirect to avoid duplicate content penalties with search engines. Also includes a Feedburner redirect. [Full Review]

– Tags –

– Video –

  • All-in-One Video Pack – All-in-One Video Pack includes every functionality you might need for video and rich-media, including the ability to upload/ record/import videos directly to your post, edit and remix content with an online video editor, enable video responses, manage and track your video content, create playlists, etc. [Full Review]

WordPress hack: Show your top contributors without a plugin

WordPress hack: Show your top contributors without a plugin

Simply paste this code where you want your top contributors to be displayed. Note that this code use the mysql_* functions instead of the $wpdb object. This is not the better way to do this, but it do the trick ;)

<?php
include($_SERVER['DOCUMENT_ROOT']."/wp-config.php");
mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME) or die(mysql_error());

$sql = "SELECT
".$table_prefix.users.".".user_login.",count(*)\n"
    . "FROM
".$table_prefix.posts.",".$table_prefix.users."\n"
    . "WHERE ".$table_prefix.posts.".".post_parent."=0
and
".$table_prefix.posts.".".post_author."=".$table_prefix.users.".".ID."\n"
    . "Group by
".$table_prefix.users.".".user_login."\n"
    . "Order by count(*) DESC\n"
    . "Limit 0,10";
$result = mysql_query($sql) or die(mysql_error());
echo "\n";
echo "<ul>";
while($row = mysql_fetch_array($result))
{
    echo "<li><strong>";
    echo $row['user_login'];
    echo "</strong>&nbsp";
    echo "(";
    echo $row['count(*)'];
    echo ")</li>";

}
echo "</ul>";

?>

This recipe has been submitted by Sidou. Do not hesitate to send me your recipes if you want them to appear on my site!

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

WordPress hack: Show your top contributors without a plugin

WordPress tip: allow upload of more file types

WordPress tip: allow upload of more file types

Simply paste the following code on your functions.php file. If needed, you can add more file types by adding them on line 4, separated by a pipe (|)

<?php
function addUploadMimes($mimes) {
    $mimes = array_merge($mimes, array(
        'tmbundle|tmCommand|tmDragCommand|tmSnippet|tmLanguage|tmPreferences' => 'application/octet-stream'
    ));

    return $mimes;
}
?>

add_filter('upload_mimes', 'addUploadMimes');

Thanks to Pioupioum for this great piece of code!

By the way, I’m running a contest at CatsWhoBlog where you can win premium WordPress themes. Click here to join!

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

WordPress tip: allow upload of more file types

10 examples of futuristic CSS3 techniques

10 examples of futuristic CSS3 techniques

Pure CSS speech bubbles

In a design, bubbles can be great to illustrate a quote. In this article, talented designer Nicolas Gallagher will show you what he built with CSS3: Text bubbles, with no Javascript or images.

Source: http://nicolasgallagher.com/demo/pure-css-speech-bubbles/bubbles.html

Super Awesome Buttons with CSS3 and RGBA

CSS has always been great to enhance buttons; but using CSS3, the RGBa property, and of course a lot of creativity, you can create modern and clean buttons. The folks at Zurb will show you how in this great tutorial. Note that I enjoyed that technique so much that I used it on my own comment form!

Source: http://www.zurb.com/article/266/super-awesome-buttons-with-css3-and-rgba

Classy photo frame using CSS3

As I recently said on my other blog Cats Who Blog, images are very important in blogging, and in the Internet media in general.
In order to enhance your images and give them a unique look and feel, the box-shadow CSS3 property is a must. Here is the code used in the example below:


Source: http://www.change.org/actions/view/tell_the_senate_protect_polar_bears_from_global_warming

Easily Turn Your Images Into Polaroids with CSS3

Although this technique can be considered as experimental only (It doesn’t work on IE, as you can expect…), I have to admit that I was surprised to see that this demo only uses CSS3 and no Javascript at all.
The tutorial will show you how to use CSS3 to transform a simple image into a Polaroid.

Source: http://www.zurb.com/article/305/easily-turn-your-images-into-polaroids-wi

Fancy web form with field hints using only CSS3

Web forms are very important because this is the main way for your visitor to get in touch with you. But styling web forms isn’t easy, and in most web sites, forms are boring and quite ugly.
The following post will show you how to use CSS3 to create a stylish web form with field hints. And no, it does not require any Javascript.

Source: http://www.skyrocketlabs.com/articles/css3-web-form-hints.php

CSS3 Drop down Menu

Ah, drop down menus. Those are extremely popular and every designer or developer had to work with at least one in his career. So what about using the power of CSS3 to enhance drop downs? In this article, talented web designer Nick La will show you how to proceed. And I must say that the result is absolutely fantastic.

Source: http://www.webdesignerwall.com/tutorials/css3-dropdown-menu/

CSS 3 selectors explained

CSS3 has lots of exiting properties, such as box-shadow and border-radius. But CSS3 also introduces new selectors, which can definitely make your life easier.
Although there’s nothing hard with these new selectors, it is important to learn what new selectors are available and how they work, so you can use them in your websites. The following tutorial is simple to follow and extremely efficient; a must read for anyone who works with cascading style-sheets!

Source: http://www.456bereastreet.com/archive/200601/css_3_selectors_explained/

Recreate Mac OSX interface using CSS3

Wow! This one totally rocks. As you can see in the screenshot below, the folks from CSS3.info had fun recreating Mac OSX user interface using CSS3 and some jQuery. Unfortunately, the method they used is not detailed, but you can still view the source and learn by the example.

Source: http://www.css3.info/wp-content/uploads/2007/08/colormoduletest.html

Letterpress Text Effect Using Photoshop and CSS

Typography is definitely something that can either make a design great, or totally ruin it. CSS3 introduced some really interesting properties to enhance the texts and titles of your designs.
In this post, you’ll learn how to create a “Letterpress” effect using CSS3 and Photoshop.

Source: http://acrisdesign.com/2010/03/letterpress-text-effect-using-photoshop-and-css/

Creating a Polaroid photo viewer with CSS3 and jQuery

Seems that Polaroid’s are popular again: After the Zurb example I shown you earlier, here is another really cool way to create a gallery, using CSS3 and jQuery. The tutorial is easy to follow and the result is quite nice.

Source: http://www.marcofolio.net/webdesign/creating_a_polaroid_photo_viewer_with_css3_and_jquery.html

Any other really cool example of the power of CSS3? Let me know in a comment!

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

10 examples of futuristic CSS3 techniques

Protect your website from attacks, A htaccess trick

2009 was the black year of attacks.Thousands of sites were attacked .

Root cause of these attacks were either Script Vulnerability (for example < Joomla 1.5.7)

In this simple tutorial i am introducing you safer way to protect your website using htaccess file.

Follow these steps.

Step1.

Know your IP

Goto
http://www.whatismyip.com

and find your IP address

ie. we get our IP
Lets say

175.189.95.239
Step 2.

Protecting your admin directory

in most of the scripts you find your admin directory are

For Joomla:administrator
For WordPress:wp-admin
For Vbulletin:admincp
For most of E-commerce scripts it is :admin (for example Magento,Zen-cart,OS Commerce etc)

Please Locate your admin directory

Suppose we have our admin directory (Site backend ) as wp-admin

Now

Step3:

We are protecting our admin directory from attackers.

Now in

yoursite.com/wp-admin

find .htaccess and open it with text-editor

A.If you are sure your IP is static(call your ISP to confirm it)

add this code to your .htaccess


satisfy any
order deny,allow
deny from all
allow from 175.189.95.239
require valid-user

B.If your IP is not static (It is dynamic hence)

add this code to your .htaccess

satisfy any
order deny,allow
deny from all
allow from 175.189.
require valid-user

Going to prevent others to enter your site.
🙂

WordPress plugin: Protect your blog from malicious URL Requests

WordPress plugin: Protect your WordPress blog from malicious URL Requests ,attacks

Paste the following code into a text file, and save it as blockbadqueries.php. Once done, upload it to your wp-content/plugins directory and activate it like any other plugins. That’s all!

<?php
/*
Plugin Name: Block Bad Queries
Plugin URI: http://blancer.com
Description: Protect WordPress Against Malicious URL Requests
Author URI: http://blancer.com/
Author: BlancerVersion: 1.0
*/
global $user_ID; if($user_ID) {
  if(!current_user_can('level_10')) {
    if (strlen($_SERVER['REQUEST_URI']) > 255 ||
      strpos($_SERVER['REQUEST_URI'], "eval(") ||
      strpos($_SERVER['REQUEST_URI'], "CONCAT") ||
      strpos($_SERVER['REQUEST_URI'], "UNION+SELECT") ||
      strpos($_SERVER['REQUEST_URI'], "base64")) {
        @header("HTTP/1.1 414 Request-URI Too Long");
	@header("Status: 414 Request-URI Too Long");
	@header("Connection: Close");
	@exit;
    }
  }
}
?>

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