How To Use Thumbnails Generated By WordPress In Your Theme

Many WordPress Themes display post excerpts on blog homepage with a little thumbnail image of one of the images used within a post, but most of the WordPress themes I have seen, use some kind of external image resizing script like phpThumb or tinyThumb or they use some custom field in the post to show thumbnail image.

But WordPress has inbuilt functionality of generating thumbnails of the images you add to your post. This functionality is enabled by default unless you have explicitly set it from Media Settings in WordPress Settings panel.


Today, I’m going to show you how to use thumbnails generated by WordPress in your theme without requiring any third party script, plugin or custom field.

1. First of all set the thumbnail size to what you want in the Media Settings of WordPress.

2. Now open up index.php of your WordPress theme and inside the WordPress loop, add the following lines of code to get the path of thumbnail image of the first image in the post.

//Get images attached to the post
$args = array(
	'post_type' => 'attachment',
	'post_mime_type' => 'image',
	'numberposts' => -1,
        'order' => 'ASC',
	'post_status' => null,
	'post_parent' => $post->ID
$attachments = get_posts($args);
if ($attachments) {
	foreach ($attachments as $attachment) {
		$img = wp_get_attachment_thumb_url( $attachment->ID );
//Display image

Code Explanation: Firstly we fetch the images attached to the post in the order they were added to the post. And if images are there we fetch the path to the thumbnail image of the first image in the post using wp_get_attachment_thumb_url function.

Now you have path of the image in $img which you can use to display the post thumbnail using img tag.

If you have visited the homepage of Web Developer Plus, I am using this technique to display post thumbnails with post excerpts.

How To: AJAXify WordPress Comment Posting

There are tons of WordPress Tutorials out there, but i haven’t found a single one that explains how to AJAX-ify WordPress comment posting on blog posts. Though there are some plugins for AJAX comments, but none seem to work with WordPress 2.8 or later versions.

Today i will show you how to enable AJAX comments with client side JavaScript comment form validation on your WordPress blog step by step that should work with most versions of WordPress. We’ll be modifying the WordPress theme files to do that. In few days, i’ll be releasing a WordPress plugin that will automatically enable AJAX Comments. So, do subscribe to our RSS Feed or e-mail updates so that you are the first to know about it.

Let’s start with it.

Functions.php file

Add the following lines of code to your theme’s functions.php file. If your theme doesn’t have one, then create a new file and add it to your theme folder.

add_action('init', 'wdp_ajaxcomments_load_js', 10);
function wdp_ajaxcomments_load_js(){
		wp_enqueue_script('ajaxValidate', get_stylesheet_directory_uri().'/wdp-ajaxed-comments/js/jquery.validate.min.js', array('jquery'), '1.5.5');
		wp_enqueue_script('ajaxcomments', get_stylesheet_directory_uri().'/wdp-ajaxed-comments/js/ajax-comments.js',	array('jquery', 'ajaxValidate'), '1.1');
add_action('comment_post', 'wdp_ajaxcomments_stop_for_ajax',20, 2);
function wdp_ajaxcomments_stop_for_ajax($comment_ID, $comment_status){
	if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
	//If AJAX Request Then
			case '0':
				//notify moderator of unapproved comment
			case '1': //Approved comment
				echo "success";
				$commentdata=&get_comment($comment_ID, ARRAY_A);
				$post=&get_post($commentdata['comment_post_ID']); //Notify post author of comment
				if ( get_option('comments_notify') && $commentdata['comment_approved'] && $post->post_author != $commentdata['user_ID'] )
					wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
				echo "error";

Code Explanation: Firstly, we load required JavaScript files jQuery, jQuery Validation and ajax-comments.js using the wp_enqueue_script() function. wp_enqueue_script() accepts four parameters.

  • First is the name of the handler for JavaScript file, you can use any name here for your own custom JavaScript, but for files that wordpress include by default like jQuery, there are pre-fixed handlers like ‘jquery’.
  • Second parameter is path to JavaScript file.
  • Third parameter is the array of name of handlers of JavaScript files, which must be loaded before the specified file.
  • Last is the version number of JavaScript file which you should use in case you use caching on your blog.

The function wdp_ajaxcomments_stop_for_ajax() hooks onto the comment_post action which is triggered after a comment has been successfully added to the database. normally, what happens when you post a comment is that you are redirected back to the original post, but since we will be using AJAX, we don’t want a redirect but a message about the status of comment posted.

I recently read a nice post from David Walsh where he told about how to identify AJAX requests using $_SERVER["HTTP_X_REQUESTED_WITH"] which is populated by most JavaScript frameworks like in our case jQuery.
I used it to hook into comment_post and check whether it is AJAX request or normal request. If it is AJAX request then check the status of comment, if it is unapproved or approved, a message ‘success’ is output and moderator or post author is notified accordingly.
After identifying AJAX request, i stopped the script execution using exit statement so as to prevent the redirect.
Now rest is the job of JavaScript code.

The JavaScript Code

You will need to add two JavaScript files jquery.validate.min.js and ajax-comments.js in the js directory of your theme(Files are available at the end of article). Create the js directory and add files if it does not exist. Though jQuery is required to work, but since it is included in WordPress by default, it will automatically be loaded as we specified it as a requirement while loading JavaScript files in functions.php.

jQuery Validation plugin is used to validate comment form data.
Here’s the code and explanation for ajax-comments.js.

	var commentform=$('form[action$=wp-comments-post.php]');
	commentform.prepend('<div id="wdpajax-info" ></div>');
	var infodiv=$('#wdpajax-info');
		submitHandler: function(form){
			//serialize and store form data in a variable
			var formdata=commentform.serialize();
			//Add a status message
			//Extract action URL from commentform
			var formurl=commentform.attr('action');
			//Post Form with data
				type: 'post',
				url: formurl,
				data: formdata,
				error: function(XMLHttpRequest, textStatus, errorThrown){
					infodiv.html('<p class="wdpajax-error" >You might have left one of the fields blank.</p>');
				success: function(data, textStatus){
						infodiv.html('<p class="wdpajax-success" >Thanks for your comment. We appreciate your response.</p>');
						infodiv.html('<p class="wdpajax-error" >Error in processing your form.</p>');

Code Explanation: Firstly, we append a div to comment form that will show AJAX status messages. Then we intialize jQuery Validation on comment form and if validation is successful, we will use jQuery AJAX to send the form data to the action URL of comment form and display a message accordingly.

Now, uptill here, if you have followed along and worked as told, you’ll find that AJAX comment posting works but validation doesn’t. Since, we are using jQuery Validation plugin, you will have to now edit the theme’s comments.php file.

Enable Comment Form Validation

Open your theme’s comments.php and add some CSS classes to comment form input fields as described:

  • To comment author name input, add class="required"
  • To comment author email input, add class="required email"
  • To comment author URL input, add class="url"
  • To the comment textarea, add class="required"

Now the comment form validation should work. But it might be having awkward looks or styles, now the last step is to customize the looks of messages using CSS.

Customize the Styles of Messaages

The error messages from validation use labels with CSS class error. While the AJAX post request status messages use two CSS classes, wdpajax-success for AJAX success and wdpajax-error for error message. Define the styles for these classes in your theme’s stylesheet file. Here’s what i have used:

	border:1px solid #f9d9c9; 
	border:1px solid #339933; 
	float:none !important; 

There you are with cool AJAX comments on your WordPress Blog.



If you find modifying theme file difficult, or if you regularly change your blog’s theme then it will be difficult for you to modify theme files every-time you apply a new theme. so, i have created a plugin named WDP AJAX Comments that will automatically add AJAX commenting to your blog.


10 Useful Advanced Git Commands

I have been using git for quite some time now and thought of sharing some advanced git commands that you may find useful whether you are working in a team environment or on your personal project.

1. Export changes done in last commit

This command i have been using regularly for sending the changes done to another person for review/integration who is not on git. It will export the recent committed changed files to a zip file.

git archive -o ../ HEAD $(git diff --name-only HEAD^)

2. Export changed files between two commits

Similarly if you need to export changed files between two commits, you can use this one.

git archive -o ../ NEW_COMMIT_ID_HERE $(git diff --name-only OLD_COMMIT_ID_HERE NEW_COMMIT_ID_HERE) 

3. Clone a specific remote branch

If you wish to clone only specific branch from a remote repository without having to clone whole of the repository branches, this will be useful to you.

git init
git remote add -t BRANCH_NAME_HERE -f origin REMOTE_REPO_URL_PATH_HERE
git checkout BRANCH_NAME_HERE

4. Apply patch from Unrelated local repository

If you need to apply a patch from a commit on some other unrelated local repository to your current repository, here is a shortcut way to do that

git --git-dir=PATH_TO_OTHER_REPOSITORY_HERE/.git format-patch -k -1 --stdout COMMIT_HASH_ID_HERE| git am -3 -k

5. Check if your Branch changes are part of Other branch

cherry command lets you check whether your branch’s changes are present in some other branch or not. It will display the changes on current branch to given branch and indicate with a + or – sign to indicate if that commit is merged or not. + indicated not present while – indicates present in the given branch. Here is how to do that:

#For example: to check with master branch
git cherry -v master

6. Start a new Branch with No History

Sometimes you need to start a new branch and do no want to carry the long history along, for example, you want to place the code in public domain(open source) but do no want to share the history.

git checkout --orphan NEW_BRANCH_NAME_HERE

7. Checkout File from Other Branch without Switching Branches

Here is how to fetch just that file you need from other branch without even have to switch branches.


8. Ignore Changes in a Tracked File

If you are working in a team and all of them are working on same branch, chances are you are going to use fetch/merge quite often. but this sometimes resets your environment specific config files which you have to change every time after merge. Using this command, you can ask git to ignore the changes to specific file. So next time you do merge, this file won’t be changed on your system.

git update-index --assume-unchanged PATH_TO_FILE_HERE

9. Check if committed changes are part of a release

The name-rev command can tell you the position of a committ with respect to a last release. Using this you can check if your changes were part of the release or not.

git name-rev --name-only COMMIT_HASH_HERE

10. Pull with rebase instead of merge

If you are working in a team which is working on same branch, then you have to do fetch/merge or pull quite often. Branch merges in git are recorded with merge commit to indicate when a feature branch was merged with mainstream. But in the scenario of multiple team members working on same branch, the regular merge causes multiple merge messages in the log causing confusion. So you can use rebase with pull to keep the history clear of useless merge messages.

git pull --rebase

Also, you can configure a particular branche to always rebasing:

git config branch.BRANCH_NAME_HERE.rebase true

Create Flipping Content Tabs Using jQuery

Content Tabs have become more popular lately with more and more websites and blogs using them to show more content in lesser space. Today I am going to show you how to create content tabs with nice flipping effect.

For this, you will need the QuickFlip jQuery Plugin by Jon Raasch and of course, the latest version of the incredible jQuery library.

The HTML Structure

Here’s the HTML structure you’ll need to use:

<div id="flip-tabs" >
	<ul id="flip-navigation" >
		<li class="selected"><a href="#" id="tab-0"  >Recent</a></li>
		<li><a href="#" id="tab-1" >Popular</a></li>
		<li><a href="#" id="tab-2" >Comments</a></li>
	<div id="flip-container" >
			<!--Put Content for first tab here-->
			<!--Put Content for second tab here-->
			<!--Put Content for third tab here-->

You can add as many tabs as you like just add more div tags inside the flip-container div and to make them accessible, do add entries in the flip-navigation list to make navigation tab for new div’s. The id field of a tag in the flip-navigation list items is important.
The id’s are of type tab-x where x is the index of the content div in the flip-container. The index starts from zero, so if you add a new div below the third content div, then the id of the navigation link corresponding to it will be tab-3.

Another thing to keep in mind is the selected CSS class, that is added to the navigation item corresponding to currently open content tab.

The CSS Styles

Here are a few styles i applied to the above HTML structure. These can be customized to whatever you want.

	margin:20px auto; position:relative;
	margin:0 0 10px; padding:0; 
#flip-navigation li{ 
#flip-navigation li a{
	text-decoration:none; padding:10px; 
	color:#333; outline:none;
	font-family:Arial; font-size:12px; text-transform:uppercase;
#flip-navigation li a:hover{
#flip-navigation li.selected a{
	font-family:Arial; font-size:13px;
#flip-container div{ 

The JavaScript Code

Finally, the javascript code that will make your flipping content tabs work:

	//initialize quickflip
	$('#flip-navigation li a').each(function(){
			$('#flip-navigation li').each(function(){
			//extract index of tab from id of the navigation item
			var flipid=$(this).attr('id').substr(4);
			//Flip to that content tab
			$('#flip-container').quickFlipper({ }, flipid, 1);
			return false;

Code Explanation: On document ready, we initialize the quickflip plugin as on Line 3 by calling it for flip-container div. One thing to keep in mind is that if you change the id of flip-container div, remember to change it in JavaScript too.
After that the click event of navigation list is controlled and on click, the clicked item is added the selected CSS class and we call the quickFlipper() function to flip to the selected content tab.

quickFlipper() function allows you to control the speed of flipping by providing options in the first parameter. e.g.

quickflipper({ openSpeed:200, closeSpeed:250 }, flipid, 1);

Also, do not change the value third parameter which is the number of times the flip event occurs. You can read more about quickFlipper function here.

Collapsible Drag & Drop Panels Using jQuery

Drag n Drop panels are great to let the user control how he/she wants to see the information as he can arrange various information blocks according to his preference. This type of functionality is often provided by web portals or personal homepage services like iGoogle.

Similarly, WordPress dashboard also lets user control how the various boxes are displayed.

Today, i am going to show you how to create collapsible, drag and drop panels easily using jQuery and jQuery UI libraries. Here’s what the final result will look like.

Let’s begin with it.

Include The Libraries

We’ll be using the all powerful jQuery library and the jQuery UI libraries, so grab the latest version of both and add it to your page header.

The HTML Structure

We’ll be using two vertical columns defined by div with class="column" in this example that will hold our panels. You can increase the number of panels by adjusting the width in the stylesheet for .column. Each panel is a div with class="dragbox". And the content of each panel resides within div with class="dragbox-content".

Here’s the complete HTML structure for our example, i will be using 5 panels within two columns.

	<div class="column" id="column1">
		<div class="dragbox" id="item1" >
			<h2>Handle 1</h2>
			<div class="dragbox-content" >
				<!-- Panel Content Here --> 
		<div class="dragbox" id="item2" >
			<h2><span class="configure" ><a href="#" >Configure</a></span>Handle 2</h2>
			<div class="dragbox-content" >
				<!-- Panel Content Here -->
		<div class="dragbox" id="item3" >
			<h2>Handle 3</h2>
			<div class="dragbox-content" >
				<!-- Panel Content Here -->
	<div class="column" id="column2" >
		<div class="dragbox" id="item4" >
			<h2>Handle 4</h2>
			<div class="dragbox-content" >
				<!-- Panel Content Here-->
		<div class="dragbox" id="item5" >
			<h2>Handle 5</h2>
			<div class="dragbox-content" >
				<!--Panel Content Here--> 

You can add a link to configuration of a panel within the <h2> tag using <span class="configure">. This will show up when mouse hovers over the panel header.

Each column now has a unique id and every panel also has a unique id, this will help in saving the order of panels if the user changes them.

The CSS Styles

Here are the CSS styles, you can modify it as you wish but remember to adjust the width of .column in case you increase the number of columns.

.column .dragbox{
	margin:5px 2px  20px;
	border:1px solid #ddd;
.column .dragbox h2{
	border-bottom:1px solid #eee;
	min-height:100px; margin:5px;
	font-family:'Lucida Grande', Verdana; font-size:0.8em; line-height:1.5em;
.column  .placeholder{
	background: #f0f0f0;
	border:1px dashed #ddd;
.dragbox h2.collapse{
	background:#f0f0f0 url('collapse.png') no-repeat top right;
.dragbox h2 .configure{
	font-size:11px; font-weight:normal;
	margin-right:30px; float:right;

The JavaScript Code

To make the boxes draggable and droppable, we’ll be using the Sortables function of jQuery UI library. Here’ the code you need to use, add this to $(document).ready() function:

	connectWith: '.column',
	handle: 'h2',
	cursor: 'move',
	placeholder: 'placeholder',
	forcePlaceholderSize: true,
	opacity: 0.4,

Explanation: I used some options with sortable function . the first one connect With lets you move panels across different columns. The handle defines the tag which is used to drag the panel. The placeholder parameter is the CSS class to use for the panel placeholder which is displayed when you drag a panel to show the possible position of the dragged panel. force, Place, holder, and Size makes sure that placeholder size is equal to the size of the dragged panel and at last opacity sets the opacity of the panel while dragging.

Collapsing The Panels
To collapse the content of a panel when you click on the panel header and show the configure link on panel header on hover, use the below code in jQuery document ready function.

	}, function(){
		$(this).find('.configure').css('visibility', 'visible');
	}, function(){
		$(this).find('.configure').css('visibility', 'hidden');
	.find('.configure').css('visibility', 'hidden');

One thing you’ll notice after adding this code is that when you drag the panel, the content of the panel toggles as when you drag the click event of panel header also fires that toggles the state of content. To fix this, you need to add another parameter to sortable so that when drag is finished, state of content does not toggle.

	connectWith: '.column',
	handle: 'h2',
	cursor: 'move',
	placeholder: 'placeholder',
	forcePlaceholderSize: true,
	opacity: 0.4,
	stop: function(event, ui){

Here i added another parameter stop that defines the function to use when drag is complete. Once the drag is complete, click event of panel header is fired so that the original state of content is restored.

Saving State

Many of the commentors below asked about how to save the state of panels. I have written a follow up post on how to save state using database. Be sure to check it if you want to know.

There you are with nice multi-column collapsible drag drop panels.

21 Amazing CSS Techniques You Should Know

Cascading Style Sheets(CSS) is one of the building blocks of modern web design without which websites would have been ugly just like they were a decade ago. With time, the quality of CSS tutorials out there on the web has increased considerably. Here are 21 amazing CSS Techniques that you might not have thought could be done by CSS.

1. Cross Browser CSS SlideShow

Amazing demonstration of how to create a cross browser image gallery using just CSS.

2. CSS Based Image Maps

This tutorial demonstrates a crazy way to create an image map using just CSS.

3. No JavaScript LightBox Using CSS

Create a lighbox using just CSS with no JavaScript required.

4. Image Replacement for Buttons

Replace the submit buttons with images using CSS, degrades back to submit button if CSS is disabled.

5. Animated Navigation Menu using CSS

Amazing tutorial on how to create an animated navigation menu using just CSS.

6. Tree Like Navigation Using CSS

Create a tree like navigation from nested lists of links. Very useful for creating sitemaps.

7. CSS Gradient Text Effect

Create eye-catching titles with nice gradient effect using just CSS.

8. CSS Menu List Design

Very easy to understand tutorial on how to create a menu list using either CSS border-style or background-image property.

9. Creating Liquid Layouts With Negative Margins

Amazing way to create a liquid layout using negative margins

10. Making Your Footer Stay Put With CSS

This might occur to you some time when a content page has not enough content to fill the page, so footer also moves up due to this. This tutorial shows you how to deal with this and make footer stay at bottom even when content is not enough.

11. Simple,Scalable CSS Based BreadCrumbs

Create a nice scalable breadcrumb navigation

12. Snazzy Pullquotes for Your Blog

Make the blockquotes in your content or blog posts standout from rest of content. Very useful to highlight major points in long content pages.

13. CSS Stacked Bar Graphs

Display graphs on your website using just CSS without any JavaScript or other heavy plugins.

14. How To Create a Block Hover Effect For List of Links

15. Multi-Column Lists

This article shows all possible ways you can use to stack up an unordered list into multiple columns.

16. Date Display Technique with Sprites

If you have ever visited Learning jQuery then you might have noticed the awesome date display next to each blog post. This tutorial will show you how to achieve that using CSS Sprites.

17. Date Badges and Comment Bubbles for your Blog

Display date and comments on your blog posts in a nice way that takes less space.

18. How To Build a CSS Image Viewer The Clever Way

Create a nice image viewer using CSS that will work even if user has disabled flash and JavaScript in the browser.

19. Creating a CSS Image Preloader

Use the CSS background-image property to preload images without any javascript required.

20. Fade Out The Bottom of Pages

This tutorial shows you how to make page content fade away into the bottom of the page just like the blog.

21. Creative and Cool Uses of the CSS Border Property

This article shows you how the CSS Border property can be used to achieve some cool effects. You’ll be surprised to know how cool the CSS Border property is.

25 Incredibly Useful CSS Tricks You Should Know

Here are 25 incredibly useful CSS tricks that will help you design great web interfaces. You might be aware of some or all of these techniques, but this can be your handy resource to nifty CSS tricks that you should know.

1. Change Text Highlight Color

You might not have known this before! With CSS you can control the colors of selected test at least for standards compliant cutting edge browsers like Safari or Firefox.

::selection{ /* Safari and Opera */
::-moz-selection{ /* Firefox */

2. Prevent Firefox Scrollbar Jump

Firefox usually hides the vertical scrollbar if size of the content is less than the visible window but you can fix that using this simple CSS trick.

html{ overflow-y:scroll; }

3. Print Page Breaks

While most of the internet users prefer to read content online but some of your users might like to print your article. With CSS you can control the page breaks within content just add this CSS class to your stylesheet and add this class to any tag which you would like to print on next page.

.page-break{ page-break-before:always; }

4. Using !important

Experienced CSS programmers are usually aware of this but beginners do miss out on this !important CSS rule. By adding !important to your CSS rule, you can increase its precedence over other subsequent rules. e.g. in below code, background-color will be blue and not red due to !important.

.page { background-color:blue !important;   background-color:red;}

5. Replace Text With Image

This is a nice SEO trick that lets you show a nice fancy image instead of simple boring text to your visitors but search engines will see only the text.

	background:url('someimage.jpg') no-repeat; 
	height: 100px; /*dimensions equal to image size*/

6. Cross Browser Minimum Height

Internet Explorer does not understand the min-height property but here’s the CSS trick to accomplish that in IE.

	height:auto !important;/*all browsers except ie6 will respect the !important flag*/
	height:500px;/*Should have the same value as the min height above*/

7. Highlight links that open in a new window

This piece of CSS code will highlight links that open in a new window so that user knows before hand that link will pop open in a new tab or window.

a[target="new"]:before {
	margin:0 5px 0 0;
	outline:1px solid #333;
	font:12px "Zapf Dingbats";
	content: "\279C";

8. Style Your Ordered List

Style numbers of an ordered list in different way than the content of each list item.

ol {
	font: italic 1em Georgia, Times, serif;
	color: #999999;
ol p {
	font: normal .8em Arial, Helvetica, sans-serif;
	color: #000000;

9. Drop Caps Using CSS


You can create a drop caps effect like those in newspapers or magazines using the :first-letter pseudo element.

margin:5px 0 0 5px;

10. Cross Browser Opacity

Though CSS3 standard includes the opacity property, but not every browser supports it, here’s the CSS trick for cross browser transparency.

.transparent_class {
	-khtml-opacity: 0.5;
	opacity: 0.5;

11. Vertical centering with line-height

If you are using fixed height container and need to vertically center the text, use the line-height property to do that perfectly.


12. Center Fixed Width layout

If you use fixed width layout, you should center the layout so that if somebody views it on larger screen, the page displays in the center of the screen and not on left side.

	margin:0 auto; 

13. Remove vertical textarea scrollbar in IE

IE adds a vertical scrollbar to textarea input fields regardless of the height of content in it. You can fix that with this simple CSS trick.


14. Remove active link borders

Some browsers like Firefox and IE add a dotted outline border over the link user clicked. It is a useful accessibility feature that lets user know which link he clicked or is in focus. But sometimes you need to get rid of this, here’s the CSS you need to use.

a:active, a:focus{ outline:none; }

15. Prevent Elements from disappearing in IE

Sometimes IE behaves in a peculiar way and makes some elements disappear, which appear when you try to make a selection. It is due to some IE issues with float elements. This can be fixed by adding position:relative; to elements that disappears.

16. Attribute-Specific Icons

CSS Attribute selectors are very powerful giving you many options to control styles of different elements e.g. you can add an icon based on the href attribute of the a tag to let the user know whether link points to an image, pdf, doc file etc.

a[href$='.doc'] { 
	padding:0 20px 0 0; 
	background:transparent url(/graphics/icons/doc.gif) no-repeat center right; 

17. CSS Pointer Cursors

This trend has caught up lately. All user interface elements on a web page that can be clicked by user have their cursor similar to that of hyperlink. Here’s the CSS trick to do that.

input[type=submit],label,select,.pointer { cursor:pointer; }

18. Capitalize Text

This trick is especially useful for displaying title of an article on a web page with all its words starting with capital letter.

text-transform: capitalize;

19. Small Caps Text

This is one of the lesser used but useful CSS property. It capitalizes all the letters of text but the size of letters following the first letter of each word is smaller than the first letter.


20. Highlight Text Input Fields

This CSS trick lets you highlight the input field currently in focus. This trick does not work in IE though.

input[type=text]:focus, input[type=password]:focus{ 
	border:2px solid #000; 

21. Remove Image Border

Image hyperlinks usually get a ugly blue border that makes your image hyperlinks look horrible. It’s better to remove border on all hyperlinked images and add individually to those you want using CSS classes.

a img{ border:none; }

22. Tableless Forms Using labels

Tableless Forms using labels and CSS
Gone are the days when tables were used to layout Forms. CSS lets you make accessible forms with table like layout using label tags. Using label tags makes sure your forms are more accessible. Here’s sample html and css code for tableless form using labels.

<form method="post" action="#" >
	<p><label for="username" >Username</label>
		<input type="text" id="username" name="username" />
	<p><label for="password" >Username</label>
		<input type="password" id="password" name="pass" />
	<p><input type="submit" value="Submit" /></p>
p label{ 

23. Set a Consistent Base Font Size

Setting the font-size property to 62.5% in body tag makes 1em equal to 10px. This lets you use em easily as you can find out the font-size in pixels from em values.

body{ font-size:62.5%; }

24. Highlight Acronym and Abbr Tags

acronym and abbr tags provide useful information to users, browsers and search engines about acronyms and abbreviations, but most of the browsers except Firefox do not highlight them. Here’s the CSS trick to highlight acronym and abbr tags within your web page.

acronym, abbr{ 
	border-bottom:1px dotted #333; 

25. CSS Reset by Eric Meyer

This piece of CSS code resets all the browser default styles preventing any browser inconsistencies in your CSS styles.

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;

21 Really Useful & Handy PHP Code Snippets

PHP is the most widely used web based programming language that powers millions of websites including some of the most popular ones like Facebook. Here are 21 really useful and handy PHP code snippets that every type of PHP developer will find useful.

1. Human Readable Random String

This code will create a human readable string that will look more close to dictionary words, useful for captchas.

*@length - length of random string (must be a multiple of 2)
function readable_random_string($length = 6){
    srand ((double)microtime()*1000000);
    $max = $length/2;
    for($i=1; $i<=$max; $i++)
    return $password;

2. Generate a Random String

If you don’t need human readable string, then use this function instead, which will create a random string you can use for user id’s etc.

*@l - length of random string
function generate_rand($l){
  $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for($i=0; $i<$l; $i++) {
	  $rand.= $c[rand()%strlen($c)];
  return $rand;

3. Encode Email Address

With this snippet, you can encode any email address into HTML entities so that spam bots do not find it.

function encode_email($email='', $linkText='Contact Us', $attrs ='class="emailencoder"' )
	// remplazar aroba y puntos
	$email = str_replace('@', '@', $email);
	$email = str_replace('.', '.', $email);
	$email = str_split($email, 5);

	$linkText = str_replace('@', '@', $linkText);
	$linkText = str_replace('.', '.', $linkText);
	$linkText = str_split($linkText, 5);
	$part1 = '<a href="ma';
	$part2 = 'ilto:';
	$part3 = '" '. $attrs .' >';
	$part4 = '</a>';

	$encoded = '<script type="text/javascript">';
	$encoded .= "document.write('$part1');";
	$encoded .= "document.write('$part2');";
	foreach($email as $e)
			$encoded .= "document.write('$e');";
	$encoded .= "document.write('$part3');";
	foreach($linkText as $l)
			$encoded .= "document.write('$l');";
	$encoded .= "document.write('$part4');";
	$encoded .= '</script>';

	return $encoded;

4. Validate email Address

E-mail validation is perhaps the most used validation in web forms, this code will validate email address and also optionally check the MX records of the domain provided in email address to make email validation more robust.

function is_valid_email($email, $test_mx = false)
	if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email))
			list($username, $domain) = split("@", $email);
			return getmxrr($domain, $mxrecords);
			return true;
		return false;

5. List Directory Contents

function list_files($dir)
  		if($handle = opendir($dir))
  			while(($file = readdir($handle)) !== false)
  				if($file != "." && $file != ".." && $file != "Thumbs.db")
  					echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";

6. Destroy Directory

Delete a directory including its contents.

*@dir - Directory to destroy
*@virtual[optional]- whether a virtual directory
function destroyDir($dir, $virtual = false)
	$dir = $virtual ? realpath($dir) : $dir;
	$dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
	if (is_dir($dir) && $handle = opendir($dir))
		while ($file = readdir($handle))
			if ($file == '.' || $file == '..')
			elseif (is_dir($dir.$ds.$file))
		return true;
		return false;

7. Parse JSON Data

With most of the popular web services like Twitter providing their data through APIs, it is always helpful to know how to parse API data which is sent in various formats including JSON, XML etc.

$json_string='{"id":1,"name":"foo","email":"","interest":["wordpress","php"]} ';
echo $obj->name; //prints foo
echo $obj->interest[1]; //prints php

8. Parse XML Data

//xml string
$xml_string="<?xml version='1.0'?>
   <user id='398'>
   <user id='867'>

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node of user
foreach ($xml->user as $user)
   //access attribute
   echo $user['id'], '  ';
   //subnodes are accessed by -> operator
   echo $user->name, '  ';
   echo $user->email, '<br />';

9. Create Post Slugs

Create user friendly post slugs from title string to use within URLs.

function create_slug($string){
	$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
	return $slug;

10. Get Real IP Address of Client

This function will fetch the real IP address of the user even if he is behind a proxy server.

function getRealIpAddr()
	if (!empty($_SERVER['HTTP_CLIENT_IP']))
	elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
	//to check ip is pass from proxy
	return $ip;

11. Force file Download

Provide files to the user by forcing them to download.

*@file - path to file
function force_download($file)
    if ((isset($file))&&(file_exists($file))) {
       header("Content-length: ".filesize($file));
       header('Content-Type: application/octet-stream');
       header('Content-Disposition: attachment; filename="' . $file . '"');
    } else {
       echo "No file selected";

12. Creating a Tag Cloud

function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
	$minimumCount = min($data);
	$maximumCount = max($data);
	$spread       = $maximumCount - $minimumCount;
	$cloudHTML    = '';
	$cloudTags    = array();

	$spread == 0 && $spread = 1;

	foreach( $data as $tag => $count )
		$size = $minFontSize + ( $count - $minimumCount ) 
			* ( $maxFontSize - $minFontSize ) / $spread;
		$cloudTags[] = '<a style="font-size: ' . floor( $size ) . 'px' 
		. '" class="tag_cloud" href="#" title="\'' . $tag  .
		'\' returned a count of ' . $count . '">' 
		. htmlspecialchars( stripslashes( $tag ) ) . '</a>';
	return join( "\n", $cloudTags ) . "\n";
****   Sample usage    ***/
$arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43, 
	'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42, 
	'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30, 
	'Extract' => 28, 'Filters' => 42);
echo getCloud($arr, 12, 36);

13. Find Similarity Between Two Strings

PHP includes a function similar_text very rarely used but quite useful that compares two strings and returns the percentage of similarity between two.

similar_text($string1, $string2, $percent);
//$percent will have the percentage of similarity

14. Use Gravatars in Your Application

With ever increasing popularity of WordPress, Gravatars have become quite popular. It is very easy to integrate them into your application as they provide a very easy to use API.

*@email - Email address to show gravatar for
*@size - size of gravatar
*@default - URL of default gravatar to use
*@rating - rating of Gravatar(G, PG, R, X)
function show_gravatar($email, $size, $default, $rating)
	echo '<img src="'.md5($email).
		'&default='.$default.'&size='.$size.'&rating='.$rating.'" width="'.$size.'px" 
		height="'.$size.'px" />';

15. Truncate Text at Word Break

This function will truncate strings only at word breaks which can be used to show a teaser for complete article without breaking words.

// Original PHP code by Chirp Internet: 
// Please acknowledge use of this code by including this header. 
function myTruncate($string, $limit, $break=".", $pad="...") { 
	// return with no change if string is shorter than $limit  
	if(strlen($string) <= $limit) 
		return $string; 
	// is $break present between $limit and the end of the string?  
	if(false !== ($breakpoint = strpos($string, $break, $limit))) {
		if($breakpoint < strlen($string) - 1) { 
			$string = substr($string, 0, $breakpoint) . $pad; 
	return $string; 
/***** Example ****/
$short_string=myTruncate($long_string, 100, ' ');

16. Zip Files on the Fly

/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
	//if the zip file already exists and overwrite is false, return false
	if(file_exists($destination) && !$overwrite) { return false; }
	$valid_files = array();
	//if files were passed in...
	if(is_array($files)) {
		//cycle through each file
		foreach($files as $file) {
			//make sure the file exists
			if(file_exists($file)) {
				$valid_files[] = $file;
	//if we have good files...
	if(count($valid_files)) {
		//create the archive
		$zip = new ZipArchive();
		if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
			return false;
		//add the files
		foreach($valid_files as $file) {
		//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
		//close the zip -- done!
		//check to make sure the file exists
		return file_exists($destination);
		return false;
/***** Example Usage ***/
$files=array('file1.jpg', 'file2.jpg', 'file3.gif');
create_zip($files, '', true);

Source: David Walsh

17. Unzip Zip File

*@file - path to zip file
*@destination - destination directory for unzipped files
function unzip_file($file, $destination){
	// create object
	$zip = new ZipArchive() ;
	// open archive
	if ($zip->open($file) !== TRUE) {
		die (’Could not open archive’);
	// extract contents to destination directory
	// close archive
	echo 'Archive extracted to directory';

18. Prepend http to a URL

Some times you need to accept some url as input but users seldom add http:// to it, this code will add http:// to the URL if it’s not there.

if (!preg_match("/^(http|ftp):/", $_POST['url'])) {
   $_POST['url'] = 'http://'.$_POST['url'];

19. Convert URLs within String into hyperlinks

This function converts URLs and e-mail addresses within a string into clickable hyperlinks.

function makeClickableLinks($text) {
 $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',
 '<a href="\1">\1</a>', $text);
 $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',
 '\1<a href="http://\2">\2</a>', $text);
 $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
 '<a href="mailto:\1">\1</a>', $text);

return $text;

20. Resize Images on the fly

Creating thumbnails of the images is required many a times, this code will be useful to know about the logic of thumbnail generation.

*@filename - path to the image
*@tmpname - temporary path to thumbnail
*@xmax - max width
*@ymax - max height
function resize_image($filename, $tmpname, $xmax, $ymax)
	$ext = explode(".", $filename);
	$ext = $ext[count($ext)-1];

	if($ext == "jpg" || $ext == "jpeg")
		$im = imagecreatefromjpeg($tmpname);
	elseif($ext == "png")
		$im = imagecreatefrompng($tmpname);
	elseif($ext == "gif")
		$im = imagecreatefromgif($tmpname);
	$x = imagesx($im);
	$y = imagesy($im);
	if($x <= $xmax && $y <= $ymax)
		return $im;

	if($x >= $y) {
		$newx = $xmax;
		$newy = $newx * $y / $x;
	else {
		$newy = $ymax;
		$newx = $x / $y * $newy;
	$im2 = imagecreatetruecolor($newx, $newy);
	imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
	return $im2; 

21. Detect AJAX Request

Most of the JavaScript frameworks like jQuery, mootools send and additional HTTP_X_REQUESTED_WITH header when they make an AJAX request, so that you can detect AJAX request on server side.(source)

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
	//If AJAX Request Then
//something else

If you would like to recommend a snippet to include in this list to make this list a more useful resource, tell us about it in comments below.

Create a Dynamic Scrolling Content Box Using AJAX

If you have used Google Reader, then you might have noticed the way Google Reader shows feed items, it loads up few items first when you click on a feed and as you scroll down to view more items, it fetches more items dynamically and adds it to the list.

Dzone also implements this technique to show items as you scroll down the list.

Similarly, Facebook has also started using this technique to load more posts in user’s home page as you scroll down.
Today, I am going to create a similar dynamic content box that loads more content dynamically as user scrolls to the bottom of the box.

The HTML Structure

<div id="container">
	<div id="scrollbox" >
		<div id="content" >
			<p>Lorem ipsum dolor sit amet</p>
			<p>Ipsum lorem dolor amet sit</p>
			<p>Dolor lorem ipsum amet tis</p>
			<p>Lorem ipsum dolor sit amet</p>
			<p>Ipsum lorem dolor amet sit</p>
			<p>Dolor lorem ipsum amet tis</p>
			<p>Lorem ipsum dolor sit amet</p>
			<p>Ipsum lorem dolor amet sit</p>
			<p>Dolor lorem ipsum amet tis</p>
	<p><span id="status" ></span></p>

The scrollbox div is the one that has fixed width and height and houses the content div that stores the content. The status span is used to display number of loaded items or the status message of loading more items.

The CSS Styles

The height and width of scrolling div is fixed using CSS and its overflow property is set to auto so that it gets a scrollbar when content exceeds the height or width. But to prevent horizontal scrolling, i added overflow-x:hidden attribute so that scrolling only occurs up or down.

	margin:0px auto; 
	padding:40px 0; 
	overflow:auto; overflow-x:hidden; 
#container > p{ 
	font-family:Arial, sans-serif; font-size:0.75em; 
	padding:5px; margin:0; 

The Concept

Now to load more content on scroll, you will need to understand the concept behind the JavaScript code given below. To start with, i will be using, three attributes of DOM objects namely, scrollHeight, clientHeight and scrollTopscrollHeight is the actual height of the inner content of a box, i.e. the actual height of content in the scrollbox container in our case. clientHeight specifies the height of the viewport container i.e. height of the visible region which is the height of scrollbox div in our case.
The scrollTop is the distance in pixels the content which has moved up.

Here is an illustraton specifying these properties.

When the scrollTop becomes equal to scrollHeight-clientHeight, then the scroll bar has reached its bottom position, so this is the point when we need to fetch new items. To make the scrolling box more useful, i added another value called scrolloffset, which keeps track of the fact that how many pixels before the bottom the scroll bar is, so that we can start fetching new items instead of the user scrolling to the bottom and then waiting for content to load.

The JavaScript Code

Here’s the JavaScript code you will need. As always, you will need to include the latest jQuery library into your page header before this code.

function updatestatus(){
	//Show number of loaded items
	var totalItems=$('#content p').length;
	$('#status').text('Loaded '+totalItems+' Items');
function scrollalert(){
	var scrolltop=$('#scrollbox').attr('scrollTop');
	var scrollheight=$('#scrollbox').attr('scrollHeight');
	var windowheight=$('#scrollbox').attr('clientHeight');
	var scrolloffset=20;
		//fetch new items
		$('#status').text('Loading more items...');
		$.get('new-items.html', '', function(newitems){
	setTimeout('scrollalert();', 1500);

Code Explanation: The updatestatus() function counts the number of items loaded into the content and displays it in the status span. The scrollalert function checks the current scrollTop position of the scrollbox div and if the scroll bar is near the bottom area, new items are fetched using AJAX.
Here i am using new-items.html that simply displays some items for the content box as this is just a demo. In actual application, you might employ some server side script that will load next items from the result set.

The content obtained via AJAX is then appended to the content div and updatestatus() is called to update the status message. setTimeout is used so that position of the scroll bar is checked periodically and if it matches condition, then new items should be fetched.

So, there you are with a dynamic content box just like Google Reader or DZone.

Multiple File Upload With Progress Bar Using jQuery

The default browser file input boxes do not allow multiple file selection for uploading at once and also do not provide any visual clue as to how much of the files selected have uploaded. Earlier I wrote about multiple file upload using AJAX, but that did not provide multiple file selection and a progress bar.

Today I am going to show you how to create a multiple file upload form that allows multiple file selection using Ctrl/Shift keys and also displays a progress bar for each of the selected files while they are uploading.

For this tutorial, you will need the all powerful jQuery library (latest version) and SWFUpload jQuery Plugin.

Folder Structure

Place the jQuery library in js folder, extract the SWFUpload jQuery Plugin somewhere and copy the jquery. swfupload.js in the src folder to the js folder. Also, copy the swfupload folder inside vendor folder of SWFUpload jQuery Plugin to js Folder. Here’s what your folder structure should look like.

Add reference to jQuery library and then jquery.swfupload.js in the head tag of your page.

HTML Structure

Since we will be using SWFUpload, we’ll need a container that will act as placeholder for SWFUpload button, and a list to show the queue of files.

<div id="swfupload-control">
	<p>Upload upto 5 image files(jpg, png, gif), each having maximum size of 1MB(Use Ctrl/Shift to select multiple files)</p>
	<input type="button" id="button" />
	<p id="queuestatus" ></p>
	<ol id="log"></ol>

CSS Styles

Here are some CSS styles to stylize our File Uploader, modify them as you want. Important ones are .progressbar and .progress that define the progress bar for file upload, you can adjust their height and color.

#swfupload-control p{ margin:10px 5px; font-size:0.9em; }
#log{ margin:0; padding:0; width:500px;}
#log li{ list-style-position:inside; margin:2px; border:1px solid #ccc; padding:10px; font-size:12px; 
	font-family:Arial, Helvetica, sans-serif; color:#333; background:#fff; position:relative;}
#log li .progressbar{ border:1px solid #333; height:5px; background:#fff; }
#log li .progress{ background:#999; width:0%; height:5px; }
#log li p{ margin:0; line-height:18px; }
#log li.success{ border:1px solid #339933; background:#ccf9b9; }
#log li span.cancel{ position:absolute; top:5px; right:5px; width:20px; height:20px; 
	background:url('js/swfupload/cancel.png') no-repeat; cursor:pointer; }

The JavaScript Code

The JavaScript code is a bit bulkier but it is not that difficult to understand as it looks.

		upload_url: "upload-file.php",
		file_post_name: 'uploadfile',
		file_size_limit : "1024",
		file_types : "*.jpg;*.png;*.gif",
		file_types_description : "Image files",
		file_upload_limit : 5,
		flash_url : "js/swfupload/swfupload.swf",
		button_image_url : 'js/swfupload/wdp_buttons_upload_114x29.png',
		button_width : 114,
		button_height : 29,
		button_placeholder : $('#button')[0],
		debug: false
		.bind('fileQueued', function(event, file){
			var listitem='<li id="''" >'+
				'File: <em>''</em> ('+Math.round(file.size/1024)+' KB) <span class="progressvalue" ></span>'+
				'<div class="progressbar" ><div class="progress" ></div></div>'+
				'<p class="status" >Pending</p>'+
				'<span class="cancel" > </span>'+
			$('li#'' .cancel').bind('click', function(){ //Remove from queue on cancel click
				var swfu = $.swfupload.getInstance('#swfupload-control');
			// start the upload since it's queued
		.bind('fileQueueError', function(event, file, errorCode, message){
			alert('Size of the file '' is greater than limit');
		.bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){
			$('#queuestatus').text('Files Selected: '+numFilesSelected+' / Queued Files: '+numFilesQueued);
		.bind('uploadStart', function(event, file){
			$('#log li#''p.status').text('Uploading...');
			$('#log li#''span.progressvalue').text('0%');
			$('#log li#''span.cancel').hide();
		.bind('uploadProgress', function(event, file, bytesLoaded){
			//Show Progress
			var percentage=Math.round((bytesLoaded/file.size)*100);
			$('#log li#''div.progress').css('width', percentage+'%');
			$('#log li#''span.progressvalue').text(percentage+'%');
		.bind('uploadSuccess', function(event, file, serverData){
			var item=$('#log li#';
			item.find('div.progress').css('width', '100%');
			var pathtofile='<a href="uploads/''" target="_blank" >view »</a>';
			item.addClass('success').find('p.status').html('Done!!! | '+pathtofile);
		.bind('uploadComplete', function(event, file){
			// upload has completed, try the next one in the queue

Code Explanation
Since we are using SWFUpload jQuery Plugin, firstly we initialize it on the placeholder element using the $('#placeholder').swfupload({ settings }) function and pass it a settings object that defines various parameters like server side file that will handle uploads, maximum size of the file, number of maximum uploads, allowed file types, button url, button size etc. For complete detail of settings you can use, refer to SWFUpload docs.

At this stage, your file upload script will work but will not show any visual clue to users about the upload. SWFUpload fires certain events that we can use to provide information to user about the file uploads. So, next thing is to bind functions to various events to show required output. That’s what all bind calls are doing. They are pretty much self-explanatory.


Since this script uses SWFUpload to upload files, which requires flash plugin, so this will not work if flash plugin is not installed in end user’s browser. Make sure to provide an alternative upload form so that users without flash can upload files.

Also, SWFUpload has some known issues when used on linux systems and if user is behind proxies. Make sure to read them before you use it in production environment.