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

MVC for Noobs

MVC for Noobs

Model-View-Controller (MVC) is probably one of the most quoted patterns in the web programming world in recent years. Anyone currently working in anything related to web application development will have heard or read the acronym hundreds of times. Today, we’ll clarify what MVC means, and why it has become so popular.


Ancient History…

MVC is not a design pattern, it is an Architectural pattern that describes a way to structure our application and the responsibilities and interactions for each part in that structure.

It was first described in 1979 and, obviously, the context was a little bit different. The concept of web application did not exist. Tim Berners Lee sowed the seeds of World Wide Web in the early nineties and changed the world forever. The pattern we use today for web development is an adaptation of the original pattern.

The wild popularization of this structure for web applications is due to its inclusion in two development frameworks that have become immensely popular: Struts and Ruby on Rails. These two environments marked the way for the hundreds of frameworks created later.


MVC for Web Applications

The idea behind the Model-View-Controller architectural pattern is simple: we must have the following responsibilities clearly separated in our application:

The application is divided into these three main components, each one in charge of different tasks. Let’s see a detailed explanation and an example.

Controller

The Controller manages the user requests (received as HTTP GET or POST requests when the user clicks on GUI elements to perform actions). Its main function is to call and coordinate the necessary resources/objects needed to perform the user action. Usually the controller will call the appropriate model for the task and then selects the proper view.

Model

The Model is the data and the rules applying to that data, which represent concepts that the application manages. In any software system, everything is modeled as data that we handle in a certain way. What is a user, a message or a book for an application? Only data that must be handled according to specific rules (date can not be in the future, e-mail must have a specific format, name cannot be more than x characters long, etc).

The model gives the controller a data representation of whatever the user requested (a message, a list of books, a photo album, etc). This data model will be the same no matter how we may want to present it to the user, that’s why we can choose any available view to render it.

The model contains the most important part of our application logic, the logic that applies to the problem we are dealing with (a forum, a shop, a bank, etc). The controller contains a more internal-organizational logic for the application itself (more like housekeeping).

View

The View provides different ways to present the data received from the model. They may be templates where that data is filled. There may be several different views and the controller has to decide which one to use.

A web application is usually composed of a set of controllers, models and views. The controller may be structured as a main controller that receives all requests and calls specific controllers that handles actions for each case.


Let’s See an Example

Suppose we’re developing an online book store. The user can perform actions such as: view books, register, buy, add items to current order, create or delete books (if he is an administrator, etc.). Let’s see what happens when the user clicks on the fantasy category to view the titles we have available.

We will have a particular controller to handle all books-related actions (view, edit, create, etc). Let’s call it books_controller.php for this example. We will also have a model, for example book_model.php, handling data and logic related to the items in the shop. Finally we will have a series of views to present, for example, a list of books, a page to edit books, etc.

The following figure shows how the user request to view the fantasy books list is handled:

The controller (books_controller.php) receives the user request [1] as an HTTP GET or POST request (we can also have a central controller, for example index.php receiving it and then calling books_controller.php).

The controller examines the request and the parameters and calls the model (book_model.php) asking him to return the list of available fantasy books [2].

The model is responsible for getting that information from the database (or wherever it is stored) [3], apply filters or logic if necessary, and return the data representing the list of books [4].

The controller will use the appropriate view [5] to present these data to the user [6-7]. If the request came from a mobile phone, a view for mobile phones will be used, if the user has a particular skin selected, the corresponding view will be chosen, and so on.


What are the Advantages?

The most obvious advantage we gain using MVC is a clear separation of presentation (the interface with the user) and application logic.

Support for different types of users using different types of devices is a common problem these days. The interface presented must be different if the request came from a desktop computer or from a cell phone. The model returns exactly the same data, the only difference is that the controller will choose a different view to render them (we can think of a different template).

Apart from isolating the view from the business logic, the M-V-C separation reduces the complexity when designing large applications. The code is much more structured and therefore easier maintain, test and reuse.


Ok, but Why a Framework?

When you use a framework, the basic structure for MVC is already prepared and you just have to extend that structure, placing your files in the appropriate directory, to comply with the Model-View-Controller pattern. Also you get a lot of functionality already written and thoroughly tested.

Take cakePHP as an example MVC framework. Once you have it installed, you’ll see three main directories:

  • app/
  • cake/
  • vendors/

The app folder is where you place your files. It is your place to develop your part of the application.

The cake folder is where cakePHP has its files and where they have developed their part (main framework functionality).

The vendors folder is for third-party PHP libraries if needed.

Your working place (app directory) has the following structure:

  • app/
    • config/
    • controllers/
    • locale/
    • models/
    • plugins/
    • tests/
    • tmp/
    • vendors/
    • views/
    • webroot/

Now you have to put your controllers in the controllers directory, your models in the models directory and your views in… the views directory!

Once you get used to your framework, you’ll be able to know where to look for almost any piece of code you need to modify or create. This organization alone makes maintainability a lot easier.


Let’s Framework our Example

Since this tutorial is not intended to show you how to create an application using cakePHP, we’ll use it only to show example code for the model, view and controller components and comment on the benefits of using an MVC framework. The code is oversimplified and not suitable for real applications.

Remember we had a book store and a curious user who wants to see the complete list of books in the fantasy category. We said that the controller will be the one receiving the request and coordinating the necessary actions.

So, when the user clicks, the browser will be requesting this url:

 www.ourstore.com/books/list/fantasy

CakePHP likes to format URLs in the form /controller/action/param1/param2 , where action is the function to call within the controller. In the old classic url format it would be:

 www.ourstore.com/books_controller.php?action=list&category=fantasy

Controller

With the help of cakePHP framework, our controller will look something like this:


<?php

class BooksController extends AppController {

 function list($category) {

 $this->set('books', $this->Book->findAllByCategory($category));

 }

 function add() { ... ... }

 function delete() { ... ... }

 ... ... } ?>

Simple, isn’t it?. This controller will be saved as books_controller.php and placed in /app/controllers. It contains the list function, to perform the action in our example, but also other functions to perform other book-related actions (add a new book, delete a new book, etc).

The framework provides a lot of things for us and only one line is necessary to list the books. We have base classes with the basic controller behavior already defined, so we inherit from them (AppController which inherits from Controller).

All it has to do in the list action is call the model to get the data and then choose a view to present it to the user. Let’s explain how this is done.

this->Book is our Model, and this part:

 $this->Book->findAllByCategory($category) 

is telling the model to return the list of books in the selected category (we’ll see the model later).

The set method in the line:

 $this->set('books', $this->Book->findAllByCategory($category)); 

Is the controller way to pass data to the view. It sets the books variable to the data returned by the model and makes it accessible to the view.

Now we just have to render the view, but this will be done automatically by cakePHP if we want the default view. If we need any other view we just have to call it explicitly using the render method.

Model

The model is even more simple:


<?php

class Book extends AppModel { 

}

?>

Why empty? Because it inherits from a base class that provides necessary functionality and we have followed the CakePHP name conventions to allow the framework to do other tasks automatically. For example, cakePHP knows, based on names, that this model is used in BooksController and that it will access a database table called books.

With this declaration only we have a book model capable of reading, deleting or saving data from the database

The code will will be saved as book.php and placed in /app/models.

View

All we have to do now is creating a view (at least one) for the list action. The view will have the HTML code and a few (as few as possible) PHP lines to loop through the books array provided by the model.


<table> <tr> <th>Title</th> <th>Author</th> <th>Price</th> </tr>

<?php foreach ($books as $book): ?> <tr> <td> <?php echo $book['Book']['title']; ?> </td> <td> <?php echo $book['Book']['author']; ?> </td> <td> <?php echo $book['Book']['price']; ?> </td> </tr> <?php endforeach; ?>

</table>

As we can see, the view doesn’t produce a complete page, just an HTML fragment (a table in this case). This is because CakePHP provides another way to define the layout of the page, and the views are inserted into that layout. The framework also provides us with some helper objects to make common task easy when creating these HTML excerpts (insert forms, links, Ajax or JavaScript).

We make this the default view saving it as list.ctp ( list is the name of the action and ctp means cake template) and placing it in /app/views/books (inside books because these are views for books controller actions).

And this completes the three components with the help of CakePHP framework!


Conclusion

We have learned what is probably the most commonly used architectural pattern today. We must be aware though that when we talk about patterns in the programming world, we are talking about flexible frames, to be tailored to the particular problem at hand. We will find implementations introducing variations on the structure we have seen, but the important thing is that, in the end, the pattern helps us gain a clear division between responsibilities and better maintainability, code-reuse, and testing.

We have also seen the advantages of using an MVC framework that provides us with a basic MVC skeleton and a lot of functionality, improving our productivity and making the development process easier. Thanks for reading!



Quick Tip: Understanding CSS3 Gradients

Quick Tip: Learning and Understanding CSS3 Gradients

Creating an image only for the purpose of displaying a gradient is inflexible, and is quickly becoming a bad practice. Unfortunately, at the time of this writing, they very well might still be required, but hopefully not for much longer. Thanks to Firefox and Safari/Chrome, we can now create powerful gradients with minimal effort. In this video quick tip, we’ll examine some of the differences in syntax when working with the -moz and -webkit vendor prefixes.


Webkit CSS3

While Mozilla and Webkit generally adopt the same syntax for CSS3 properties, they unfortunately don’t quite agree when it comes to gradients. Webkit was first to embrace gradients, and uses the following structure:

/* Syntax, taken from: http://webkit.org/blog/175/introducing-css-gradients/ */
-webkit-gradient(<type>, <point> [, <radius>]?, <point> [, <radius>]? [, <stop>]*)

/* In practice... */
background: -webkit-gradient(linear, 0 0, 0 100%, from(red), to(blue));
Webkit

Don’t worry if your eyes gloss over at that syntax; mine did too! Just note that we require a comma-separated list of parameters.

  • What type of gradient? (linear)
  • X and Y axis coordinates of where to begin. (0 0 – or left-top corner)
  • X and Y axis coordinates of where to conclude (0 100% – or left-bottom corner)
  • What color to begin with? (from(red))
  • What color to conclude with? (to(blue))

Mozilla

Firefox, which implemented gradient support with version 3.6, prefers a slightly different syntax.

/* Syntax, taken from: http://hacks.mozilla.org/2009/11/css-gradients-firefox-36/ */
 -moz-linear-gradient( [<point> || <angle>,]? <stop>, <stop> [, <stop>]* )

/* In Practice */
background: -moz-linear-gradient(top, red, blue);
Mozilla
  • Note how we’ve placed the type of gradient, linear, within the vendor extension.
  • Where should the gradient begin? (top – we could also pass in degrees, as in -45deg)
  • What color to start with? (red)
  • What color to conclude with? (blue)

Color-Stops

What if you don’t need a 100% gradient from one color to another? This is where color stops come into play. A common design technique is to apply a short and subtle gradient, like this:

Subtle Gradients

Note the subtle off-white to white gradient at the top.

In the past, the standard implementation was to create an image, set it as the background of an element, and set it to repeat horizontally. However, with CSS3, this is a cinch.

background: white; /* fallback for older/unsupporting browsers */
background: -moz-linear-gradient(top, #dedede, white 8%);
background: -webkit-gradient(linear, 0 0, 0 8%, from(#dedede), to(white));
border-top: 1px solid white;

This time, we set the gradient to conclude at 8%, rather than 100%, which is the default. Note that we’re also applying a border top to add contrast; this is very common.

If we wish to add a third (or Nth) color, we can do:

background: white; /* fallback for older/unsupporting browsers */
background: -moz-linear-gradient(top, #dedede, white 8%, red 20%);
background: -webkit-gradient(linear, 0 0, 0 100%, from(#dedede), color-stop(8%, white), color-stop(20%, red);
  • With the -moz version, we designate that, at 20% of the element height, we should now be at the color red.
  • For -webkit, we use color-stop, and pass in two parameters: where the stop should occur, and what the color should be.

Important Notes About CSS Gradients

  • Use them as much as you can. If it’s okay to let IE users see a solid color, I encourage you to use this method.
  • IE6/7/8, Opera, Safari 3, and Firefox 3 cannot render CSS3 gradients. Firefox and Safari users generally upgrade often, so that’s not as big of a deal.
  • Always apply a default, solid color, background for browsers that won’t understand the vendor prefixes.
  • Never use a red to blue gradient, as I did for the examples.
  • Webpages don’t need to look the same in every browser! :)

Setting up a Rails Server and Deploying with Capistrano on Fedora from Scratch

Setting up a Rails Server and Deploying with Capistrano on Fedora from Scratch

This article and video tutorial will teach you how to setup a basic Fedora server for Rails and PostgreSQL deployments. First, we’ll setup Apache and PostgreSQL. Then, we’ll use phpPgAdmin to create our application’s user and databases. After that, we’ll setup the Ruby platform using Passenger to run our application. Once all the components are installed, we’ll prep our application for deployment using Capistrano.

I’ll show you how to use Capistrano to automate remote tasks and take advantage of other features.


On With The Show


Understanding the Deployment Process

There is always a lot of confusion around deploying Rails applications. This tutorial hopes to sort some of that out. Most people know LAMP: Linux, Apache, MySQL, and PHP. We will setup LAPR: Linux, Apache, PostgreSQL, and Ruby. Setting up a LAPR server is very similar to setting up a LAMP server. The only wrinkle is getting Rails to talk to Apache. Thankfully, there is Passenger aka mod\_rails. Passenger is like mod\_php. It makes running Rails applications easy as pie. In order to run a Rails application through Apache, create a virtual host pointing the document root to the applications public directory and you’ll be riding on rails.

Capistrano is another part that people may not be familiar with. Capistrano is a Ruby gem designed to execute tasks on one or more remote machines. You’ll need SSH access to use Capistrano. Capistrano, affectionately known as Cap, automates the deploy process. We can use cap to take our code from some a repo and push it to the server, stop/start/restart the server, write custom tasks required by our application (think install required gems), or disable/enable a maintenance page. Using cap is not required but it sure beats using FTP to copy all the files around! Cap’s real power comes from the ability to write custom tasks in Ruby to manipulate the server. I’ve written a lot of applications that allow user file uploads. Then on the server side, some directory needs to be created with proper permissions for the uploads to succeed. It’s easy enough to write a cap task to create the directory and set the permissions. Then, if you ever change servers, you can simply run the cap task to setup the server again. There are many things you can do with Capistrano. You could even automate this entire tutorial to set up any number of machines at once!


Tutorial Sandbox

In order to complete this tutorial, you’ll need SSH + sudo access. If you don’t have a spare server sitting around, you can create one in VirtualBox. You can easily create a new VM and network it with your host system. I did this for the tutorial. When you start your virtual machine, make sure you use a bridged adapter so your VM gets an IP on the same subnet. I started with a fresh install without any customization. If you have access to a VPS like SliceHost, you can use these instructions as well.

Be sure to view the screencast before analyzing the code below.


Creating The Deployer

    $ sudo adduser -m deployer
    $ sudo passwd deployer
    $ sudo visudo deployer ALL=(ALL) NOPASSWD: ALL
    $ su deployer
    $ mkdir ~/.ssh
    $ touch ~/.ssh/authorized_keys2
    $ chmod -R 0700 ~/.ssh
    # copy your public key and paste it into the authorized_keys2 file
    $ service sshd start

Setting Up Postgres

    $ sudo yum groupinstall "PostgreSQL Database"
    $ sudo service postgresql initdb
    $ sudo service postgresql start
    $ su - postgres
    $ psql -d template1
    $ alter user postgres with password 'yourpostgresuserpassword';
    $ \q
    # Replace ident in /var/usr/lib/pgsql/data/pg_hba.conf with md5
    $ passwd postgres
    # set extra security in /etc/phpPgAdmin/config.inc.php to false
    # add 'Allow from YOUR_IP_HERE' to vhost in /etc/httpd/conf.d/phpPgAdmin.conf
    # enable http in the firewall
    $ sudo yum install httpd
    $ sudo service httpd start
    $ sudo service postgresql restart

Configuring Ruby, RubyGems, and Passenger

    $ sudo yum groupinstall Ruby
    $ sudo yum install rubygems
    $ sudo gem install gemcutter
    $ sudo yum install postgresql-devel
    $ sudo gem install pg
    $ sudo gem install passenger
    $ yum install gcc-c++ httpd-devel apr-devel
    $ sudo passenger-install-apache2-module
    # create this file /etc/http/conf.d/passenger.conf with these contents:
      LoadModule passenger_module     /usr/lib/ruby/gems/1.8/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
      PassengerRoot /usr/lib/ruby/gems/1.8/gems/passenger-2.2.9
      PassengerRuby /usr/bin/ruby

    $ sudo setenforce 0
    $ sudo service httpd restart

Creating the Deployer Folder

    $ sudo mkdir /var/www/html/apps
    $ sudo chown deployer:apache /var/www/html/apps
    $ sudo yum install git
    # at this point, create your databases in phpPgAdmin
 

Configuring Apache

    # echo "Include vhost.d/*.vhost" >> /etc/httpd/conf/httpd.conf
    $ sudo mkdir /etc/httpd/vhost.d
    $ sudo touch /etc/httpd/vhost.d/nettuts-demo.vhost
    # update that files conttents to:
      
          ServerName www.nettuts-demo.com
          DocumentRoot /var/www/html/apps/nettuts-demo/current/public
          
            Options FollowSymLinks
              Allow from all
              Options -MultiViews
          

          RewriteEngine On
          RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
          RewriteCond %{SCRIPT_FILENAME} !maintenance.html
          RewriteRule $ /system/maintenance.html [R=302,L]
      

Complete Cap File

    set :application, "nettuts-demo"
    set :repository,  "git://github.com/Adman65/Nettuts-Capistrano-Deployments.git"

    set :user, :deployer

    set :deploy_to, "/var/www/html/apps/#{application}"

    set :use_sudo, false

    set :scm, :git

    role :web, "192.168.1.112"                          # Your HTTP server, Apache/etc
    role :app, "192.168.1.112"                          # This may be the same as your `Web` server
    role :db,  "192.168.1.112", :primary => true # This is where Rails migrations will run
    role :db,  "192.168.1.112"

    default_run_options[:pty] = true

    namespace :deploy do
       task :start do ; end
       task :stop do ; end
       task :restart, :roles => :app, :except => { :no_release => true } do
         run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
       end

       desc "Installs required gems"
       task :gems, :roles => :app do
         run "cd #{current_path} && sudo rake gems:install RAILS_ENV=production"
       end
       after "deploy:setup", "deploy:gems"   

       before "deploy", "deploy:web:disable"
       after "deploy", "deploy:web:enable"
    end



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

A 15 Minute Surreal CMS Integration

A 15 Minute Surreal CMS Integration

You’ve already built your website, but how are you going to maintain it? In this tutorial, you’ll learn how to integrate your website with Surreal CMS in under 15 minutes. We’ll go over some of the “gotchas” and have you editing virtually any static website in barely no time at all.


Overview

You’re probably wondering how you could possibly integrate your entire website with a CMS in just 15 minutes. The truth is, due to the recent trend of “light” content management systems, it’s becoming easier than ever to get small to mid-sized static websites up and running in them.

What is a light CMS? For the sake of this tutorial, I’m defining it as an easy-to-use, unobtrusive content management system that you don’t have to install. The nice thing about these systems is that you don’t even have to host them yourself, which is why integration takes very little time.

There are actually a handful of these CMS products available, including CushyCMS, Pagelime, and SimpleCMS. Most of these systems work off the same basic principle — you add class=”something” to almost any HTML element, link your website up to their system, and you’re done. Best of all, every one of these systems offer a free version.

Although every light CMS product has its pros and cons, I chose to work with Surreal CMS because of their vast feature set and simple interface. You’ll see exactly what I mean in just a moment, but in the meantime, here is the general process of integrating with any light CMS:

  • Create your website
  • Link it up to the CMS
  • Enable webpages
  • Add one or more editors
  • Begin editing

Just to familiarize you with the tool that we’ll be working with, here is a quick glimpse of Surreal CMS’ webpage editing screen:


Design Considerations

Before you begin working with a light CMS, it’s always good to think about things such as character encoding and the way you link to images and other resources. Surreal CMS prefers that you use UTF-8 character encoding, which is as simple as adding the following meta tag to the <head> section of each webpage:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

It’s also important that you link to documents, images, and other resources in a way that the CMS can understand. Surreal CMS works best when you use root-relative linking or absolute linking:

<a href="/images/photo.jpg">...</a>
<a href="http://example.com/images/photo.jpg">...</a>

The last but probably most important thing to consider before linking your website up to Surreal CMS is the placement of your content regions. Here is an excellent example of a very basic webpage that has a navigation menu, a sidebar, and a main content area:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<title>Example Webpage</title>
		<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
		<meta name="description" content="This is an example webpage" />
		<meta name="keywords" content="example, examples" />
		<link href="/css/screen.css" rel="stylesheet" type="text/css" media="screen" />
	</head>

	<body>

		<div id="header">
			<h1><a href="http://example.com/">Example.com</a></h1>
		</div>

		<div id="nav">
			<?php include("$_SERVER[DOCUMENT_ROOT]/includes/nav.php"); ?>
		</div>

		<div id="middle">

			<div id="sidebar" class="editable">
				<p>Sidebar content here</p>
			</div>

			<div id="main_content" class="editable">
				<p>Your content here</p>
			</div>

		</div>

		<div id="footer">
			<p>&copy;Example.com</p>
		</div>

	</body>

</html>

You may have noticed that I added editable classes to the sidebar and the main content region. This is how the CMS knows what sections of your page it should allow you to edit. You can add the editable class to almost any HTML tag, and you can have as many as you want on each page.

Another thing you may have noticed was that the navigation is being included from a separate file via PHP. Surreal CMS allows you to work with included files like this so you can update your entire site’s navigation without having to edit each page individually.

Once you’ve prepared your pages and setup editable regions, you’ll be ready to integrate your website with Surreal CMS.


Adding Your Website to the CMS

Surreal CMS offers both free and paid accounts. The free account has very few restrictions, and will be more than sufficient for the sake of this tutorial. Simply go to their website and create a free account.

Once your account is created, login to the CMS at http://edit-content.com/. This is the gateway to the Surreal CMS application.

Now that you’re in, select the button that says Add a Website. Here is the form that you will see:

Enter your website’s URL, server (usually ftp.your-domain.com), FTP username, and FTP password. You can verify that you typed everything correctly by clicking Test Connection.

For the Website Root, it’s best to click the Browse button and use the browsing tool. Essentially, your website root will be the folder that contains your homepage. It’s important that this folder be the actual folder that has your homepage so the CMS can properly map URLs to images and other files.

If you want to specify custom paths for documents, images, and media files, select the Advanced option. When you set custom paths, it will tell the CMS where other people who are editing your website are allowed to upload files. For now, you can leave these blank.


Enabling Your Webpages

Now that your website has been added to the CMS, the next step is to enable your webpages. In other light CMS products, this can be a bit taxing on your time, but Surreal CMS has a nice scan feature that auto-enables webpages with just a click.

To begin enabling pages, select your website from the list:

Next, select Enable Webpages. The following dialog will appear:

Select the page or pages that you want to be able to edit in the CMS. As you select them, they will appear one-by-one in the background. As a shortcut, you can navigate to any directory on your website and click Scan for Editable Pages. This will tell the CMS to enable any page in the current directory that has a class=”editable” attribute in it. When you’re finished, select Done.

By default, each page that you enable uses the <title> of the page as a label. You can easily change this to something more CMS-friendly by clicking on Edit Label. For example, you might change the label for index.php to read “Homepage” and the label for nav.php to read “Navigation”.


Updating Your Content

Believe it or not, the hard part is over. Now it’s just a matter of getting in there and editing content. Part of the reason I like Surreal CMS so much is that it streamlines most of the setup. That said, let’s move on to editing content.

After you enable one or more webpages, the next step is to begin editing. Simply select any of the pages that you’ve enabled by clicking on the appropriate page label. This will take you into the webpage editor, where you’ll spend most of your time using this great CMS.

In the webpage editor, you’ll see four tabs:

  • Content – This is where all your content regions can be found.
  • Properties – You can edit the page title, keywords, and description here.
  • History – View every revision of this page that gets published for up to 90 days.
  • Editors – See a list of all the editors that have access to the page.

Inside of the Content tab, assuming your page has at least one editable region, you’ll see something like this:

This particular example has the two editable regions we talked about earlier: sidebar and main_content. You’ll notice that the CMS converted the lowercase, underscore-separated IDs into Camel Case, space-separated labels for aesthetics. If you have more than one editable region on a page, you can switch between them by clicking on the appropriate button.

At this point, editing works the same way as it does in many other content management systems and word processing applications. You can format text, change alignment, insert images, lists, etc. Surreal CMS even has a built in File Manager that lets you view, upload, rename, and delete files and folders. To top it off, there is also an Image Editor that lets you resize, crop, rotate, and flip images with ease.

Depending on the type of element that you add class=”editable” to, Surreal CMS will provide an appropriate editing tool. As an example, here is what an editable <img> looks like:

The Edit Image button launches the Image Editor that I talked about earlier. It’s really easy to use, so you shouldn’t have any trouble at all manipulating your photos. Here’s what it looks like:

Once you’re finished editing, you can preview your changes by clicking Preview. A new window will open, and you’ll see your page exactly as it will appear when published. Of course, if you’re happy with your changes, clicking Publish will save them to your website.


Allowing Other People to Edit Your Website

Now that you know how to setup your website and edit it yourself, wouldn’t it be nice to allow other people access as well? This is especially useful for designers who want to give clients limited access to edit their own websites, and it’s simple to setup.

First, select the Editors tab from anywhere in the CMS and click on Add an Editor. The following form will appear:

Simply fill in the person’s name and email address to start. Then, select the website(s) that he or she should be assigned to. If you want, you can open up the Advanced section and allow the editor to clone pages, delete pages, and edit page properties. You can also enable or disable every option in the rich-text editor toolbar from here.

Once you’ve entered all the necessary information, select Add Editor and the user will be added to the CMS. By default, an email is sent to them containing their username and password. You can disable this, however, and the CMS will show you their temporary password for you to provide them with manually.

There are a couple things that you need to know about editor accounts. First, they don’t have access to everything that you do as a designer — editors only have access based on the websites and permissions that you assign to them. Second, editors don’t have access to things like full-page source code editing and the Tidy tool, which we’ll talk about shortly. The best way to see what the difference is between a designer and an editor account is to create yourself a test editor with an alternate email address.

Before we move on, there’s one other feature that you should know about editors. You can block them from editing specific pages on a per-user basis. Simply open any page for editing and select the Editors tab. Next to your editor will be an option to Disable editing. Clicking this will prevent that user from editing the current page.


Other Handy Features

So far, we’ve covered everything from integrating Surreal CMS with your website to editing pages. The fun doesn’t stop there, though. Here is a list of features that you can take advantage of once you start to explore deeper into what Surreal CMS offers:

Cloning Webpages

You can create new pages by duplicating existing ones. This is especially useful because you can setup one or more blank template pages and let your users create pages as they need to. You can also turn this on or off for each user, so more experienced editors can have more control over the site.

Styling the Rich-text Editor

Apply styles from your website to the rich-text editor to give users a similar look and feel similar to the website. To access this feature, select the Websites tab from anywhere in the CMS and choose a website. You’ll see a button labeled Change Editor Styles.

Editing CSS, JavaScript, and XML Files

You can enable stylesheets, scripts, and XML files just like any other webpage. Of course, you’ll be editing raw source code, so you might want to block inexperienced users from accessing these types of files if you enable them.

Editing Full HTML Source Code

While you’re editing a webpage, you’ll notice a button labeled “Edit Content Regions”. This actually allows you access to the full source code of the page. Editors do not have access to this tool.

Repairing Messy HTML Code with Tidy

Surreal CMS has a built in tool that utilizes the popular HTML Tidy library. This is useful for fixing nested tags or invalid HTML code that may cause problems while editing. You can access this tool from within the full source code editing page.

Viewing Editor Activity

You can see what your editors have been up to! This includes what pages they’ve accessed, when they were edited, and even the times that they logged in to the CMS. To view this information, select the Editors tab from anywhere in the CMS and choose an editor. Click on the editors name to see their recent activity.

Pro Features

Surreal CMS is free to use for up to three websites. After that, they ask you to pay $25 USD per month for their paid service, but Pro accounts have a couple other nice features, too. For example, you can access the CMS from your own domain or subdomain (i.e. cms.your-domain.com).

With a Pro account, you can also upload your own logo and customize the theme, which is ideal for designers who want to use the CMS as a solution for their clients. Here’s an example of what you can expect when you brand the CMS as your own:


Additional Resources

Now that you know all of the basics (and some advanced tips, too!), here are some useful resources for working with Surreal CMS:



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: https://blancer.com
Description: Protect WordPress Against Malicious URL Requests
Author URI: https://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