Create Thumbnail Images with Rounded Corners

If you have been using Facebook, then you might have noticed thumbnail images with rounded corners in new Facebook homepage. If you would like to have similar effect for thumbnails in your application, then here's a quick and easy way to do it.

We'll be using phpThumb, the open source PHP script to generate thumbnails on the fly.

Download and extract phpThumb to somewhere in your website folder. Now to use a rounded corner thumbnail of an image, simply use the img tag of HTML with src as

<img src="phpThumb.php?src=test.jpg&w=200&h=150&fltr[]=ric|20|20&f=png "/>

Adjust the path to phpThumb according to where you place the phpThumb files. Now we have passed 5 parameters to phpThumb.php namely,

1. src is the path to image file relative to phpThumb.php

2. w & h are width and height of the resulting thumbnail

3. fltr is used to tell phpThumb to generate rounded corner thumbnail with first numeric value as horizontal radius of the rounded corner and second as vertical radius in pixels.

4. The last parameter f is used to control the output image format of the thumbnail, namely png, jpg or gif. We are using png as it can render images with transparent corners which can be used on any background.

That's it, you have cool looking thumbnails with rounded corners.

5 Libraries that Help You Generate Excel Reports in PHP Application

Microsoft Excel is still the most widely used data analysis, report generation tool. If you have ever worked on any enterprise application, you must have got across the requirement of having excel export facility for various reports available in your application.

Today, we will look at various options available to PHP developers for exporting data to excel spreadsheets.

 

1. PHPExcel

  1. Best in class of the available options. Well maintained and active community project.
  2. Supports images,charts, formulas, multiple worksheets.
  3. Extendable: supports exporting to pdf/doc or any other format you may like. You can extend the output writer class and use any format you need.
  4. Documentation is comprehensive and easy to understand even for beginner php programmers.
  5. Can Load existing excel files and use them as base template for filling data.
  6. Also supports openXML formats used by Open office or MS office 2007 or later.

2. php-excel

  1. Lightweight library with minimal functionality required for exporting just a data only simple excel file.
  2. Good for simple data export requiring one worksheet in the excel file.
  3. MS Office 2007 or higher will give an alert saying file may not be in proper format to user before opening the file.
  4. Supports output to browser only.
  5. No support for formulas, images, charts etc.

3. Php export data

  1. Built on top of php-excel library mentioned above.
  2. Supports export to tsv/csv format besides xls format.
  3. Supports output to browser, file or string.

4. Excel Writer(XML) for PHP

  1. Supports excel formulas.
  2. Multi sheet support.
  3. Formatting support.
  4. Supports direct export from mysql tables, mysql query.
  5. Generates files in Microsoft Office 2003 XML format which opens correctly in Microsoft excel, but the extension of the file might confuse users.

5. Pear Excel Writer

  1. Supports formulas and images.
  2. Multi sheet support
  3. Formatting support.
  4. Only BIFF format i.e. .xls can be generated. No support for newer formats.

Have you used any of these or any other library for exporting data in excel format from php application? If yes, share them in comments below.

Add Dynamic Scroll to Top Button to Your Web Pages

While reading lengthy web pages, readers often look for a link that’ll take them back to the top of the page without having to scroll upwards. Here’s a nice jQuery plugin that'll add a dynamic Scroll To Top link to your web pages. It is dynamic in the sense that it won’t show up when user is at the top of the page and will slowly fade in when page is scrolled down.

To add this dynamic Scroll to Top button, download this Scroll to Top plugin written by Craig Wilson of Ph.Creative and add a reference of jquery and this plugin in your header.

Now add a link to your web page html somewhere near your page header that'll act as Scroll to Top button.

<a id=”goToTop” href=”#” >Go To Top</a>

Now in your jQuery Ready function, add these lines to make Go To Top link dynamic.

$(“#goToTop”).scrollToTop();

10 Ways To Make Your Blog’s Comment Form Stand Out

WordPress comment form is usually the left out portion of most blog designs. Most blog designers do not care to make the comment form unique and stylish but just create it in a hurry. Here are 10 ways with examples to make your blog’s comment form stand out from the crowd.

1. Change the Layout

Most wordpress theme developers do not give much thought into changing the layout of comment form and usually use the same layout as in the default wordpress theme. By creating a different layout of comment form, you can make your blog stand out from the crowd. Here are some nice comment form layouts you can get inspiration from to create a different and unique layout for your net blog design.

Name, Email, URL in line

Name, Email, URL in line at bottom

Name, Email, URL to right

Name, Email, URL to the left

Name, Email, URL after comment area

2. Using tabindex

tabindex is the attribute for form elements using which you can decide the tab order that is where to focus next when user presses tab to proceed to next input field. By default, tab index will be the order in which input fields are present in html code. But if you change the layout, it will be better to specify tabindex attribute with input fields.

3. Use label and fieldset

The comment forms should be accessible to all, even those who use screen readers, they should be able to comment on your blog. label and fieldset tags make your comment form more accessible as screen readers use information in label tag to specify input fields.

4. Highlight Field in Focus

Highlighting the input field currently in focus makes your comment form more usable. You can use the :focus pseudo CSS selector to define styles for highlighting field in focus.
But the CSS technique does not work everywhere as older versions of IE do not recognize :focus pseudo selector. For that You can use JavaScript. Here’s the sample code in jQuery to highlight field in focus.

$('input').focus(function(){
	$(this).css('border-color', '#000');
})
.blur(function(){
	$(this).css('border-color', '#666');
});

5. Add a Formatting Toolbar to Comment textarea

This one is not that necessary but if you want to enhance user experience by providing them with options to format their comment, you should consider adding a WYSIWIG text editor toolbar to your comment textarea. Here’s a nice plugin called TinyMCE Comments that utilizes the same editor which is used in WordPress Admin area.

6. Let Users Subscribe To Comments

This is a must have feature for any WordPress blog as it lets users know if anyone has replied to their comment or added some useful information to the article. You can use Subscribe to Comments WordPress plugin to add this functionality.

7. Show Errors Instantly

In WordPress, if comment form data has some errors, users are taken to a new page that only displays error message and nothing else. As a result user has to click back button and sometimes comment data is lost which will have to be typed again.

It is always a nice idea to have form validation on the spot using JavaScript and display error messages to user as he leaves a particular field rather than form posting back to server and then coming out with errors. Here’s a nice tutorial on adding form validation with jQuery.

8. Preview Comments

Letting the user have a chance to see what they are about to post prevents not only spell mistakes or grammatical errors but also gives them a chance to have a second thought over what they have written. There are some nice plugins like Live Comment Preview to add this type of feature into WordPress comment form.
But the question is not only the preview functionality but also where the preview will be shown, Lorelle VanFossen has written a good tutorial about live comment preview position.

9. Edit Comment After Posting

10. Spice Up With Graphics

Using some fancy graphics to style your comment form will give it a unique appearance and brand. Moreover, graphics say more than words and will help catch user attention and will motivate them to comment on your blog. Here are some spicy comment forms with appropriate use of graphics.

That’s It! With a litlle thought and time, you can make your blog’s comment form more usable and enhance the user experience.

CSS Tooltip Box Without Images

The tooltip boxes you see on many websites are though created using background images but there’s another way out using just CSS  without requiring any background images. To create the tooltip box, create one outer div that encapsulates the information and the pointer div.

<div class="tooltip">
Tooltip content goes here...
<div class="pointer">
<div class="inner-pointer"></div>
</div>
</div>

Now we need to absolutely or relatively position the tooltip div so that we can control the position of pointers in the div. The pointer div acts as outer body of pointer and inner-pointer acts as inner body. Both these div are sizeless but have border. The transparent border property is used to form the pointer shapes.

You can match the border-color of inner pointer to that of tooltip div background color and pointer div to that of border color to get a uniform look of the pointer.

Here’s the CSS to use:

<style type="text/css">
body{ background:#333; }
.tooltip {
padding: .8em;
width: 12em; background:#ff3311;
border-width: 2px !important;
border-color:#999;
position: absolute;
}
.tooltip .pointer, .tooltip .inner-pointer {
position: absolute;
width:0;
height:0;
border-bottom-width: 0;
background: none;
}
.tooltip .pointer {
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-top: 14px solid #999;
bottom:Â Â Â  -14px;
right: auto;
left: 5%;
margin-left: -7px;
}
.tooltip .inner-pointer {
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid #ff3311;
bottom:Â Â Â  auto;
top: -14px;
left: -5px;
}
</style>

You can play with different border style and positioning of the pointer div to control the look of your tooltip box.

Without any use of images, these tooltip boxes will be easy on bandwidth and will load faster.

Quick & Easy Way to Implement Drag n Share With jQuery

You must have seen the drag to share functionality on Mashable that lets visitors share the content on popular social networks intuitively. Just drag one of the images in an article and you’ll be able to share the article on your favorite social network by dropping the dragged image over its icon. Even, Nettuts has written a nice tutorial on how to implement this functionality into your website using jQuery. But here is a much elegant solution to achieve the drag n share effect using jQuery with just a line or two of JavaScript code.

Get the prettySociable Plugin

To implement this functionality, you will need the prettySociable jQuery plugin written by Stéphane Caron. Download and extract the plugin, it contains everything you need to get up and running with drag n share.

Include the Required Files

To add drag n share to a page, add reference to jquery and prettySociable in your page’s head tag. The plugin folder also includes images and css folders in addition to js folder. You’ll need them too as css folder contains styles necessary for drag n share elements and images folder contains icons for various social networks.
Here’s the complete code you need to add into the head tag.

<link rel="stylesheet" href="css/prettySociable.css" type="text/css" media="screen" charset="utf-8" />
<script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<!--[if lte IE 6]><script src="js/DD_belatedPNG.js" type="text/javascript" charset="utf-8"></script><![endif]-->
<script src="js/jquery.prettySociable.js" type="text/javascript" charset="utf-8"></script>

The js folder also includes DD_belatedPNG.js which is used to fix PNG transparency issues in IE6 or older. You need to include that too.

Define Draggable Links

Now to add drag n share to your web page, add an anchor tag <a href="#" > with another attribute rel="prettySociable".

Initialize prettySociable

After you have added the rel attribute, you need to initialize the script. Add this single line of code, just above the </body>

<script type="text/javascript" charset="utf-8">
	// Init prettySociable
	$.prettySociable();			
</script>

Check out your page in browser and you should get drag to share functionality working nicely.

Customizing the Default Settings

Customizing the Shared Information

When you add rel=”prettySociable” on an anchor tag with its href=”#”, this will share the URL of the current web page and use the title and meta description in head tag to display the tooltip on drag.

But if you need to share a different URL instead of the current web page, specify a URL in the href attribute. Also you can customize the tooltip information which is shown on dragging. You can specify custom title and description in the rel attribute in this way.
rel="prettySociable;title:custom title;excerpt:custom excerpt;"

Customizing the Sharing Panel

By default prettySociable supports eight social networks but you can customize the social networks and their icons to your requirement. For that you’ll need to pass a settings object to prettySociable function.

Here’s the complete settings object

$.prettySociable({
				animationSpeed: 'fast', /* fast/slow/normal */
				opacity: 0.90, /* Value between 0 and 1 */
				share_label: 'Drag to share', /* Text displayed when a user rollover an item */
				share_on_label: 'Share on ', /* Text displayed when a user rollover a website to share */
				hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettySociable */
				hover_padding: 0,
				websites: {
					facebook : {
						'active': true,
						'encode':true, // If sharing is not working, try to turn to false
						'title': 'Facebook',
						'url': 'http://www.facebook.com/share.php?u=',
						'icon':'images/prettySociable/large_icons/facebook.png',
						'sizes':{'width':70,'height':70}
					},
					twitter : {
						'active': true,
						'encode':true, // If sharing is not working, try to turn to false
						'title': 'Twitter',
						'url': 'http://twitter.com/home?status=',
						'icon':'images/prettySociable/large_icons/twitter.png',
						'sizes':{'width':70,'height':70}
					},
					delicious : {
						'active': true,
						'encode':true, // If sharing is not working, try to turn to false
						'title': 'Delicious',
						'url': 'http://del.icio.us/post?url=',
						'icon':'images/prettySociable/large_icons/delicious.png',
						'sizes':{'width':70,'height':70}
					},
					digg : {
						'active': true,
						'encode':true, // If sharing is not working, try to turn to false
						'title': 'Digg',
						'url': 'http://digg.com/submit?phase=2&url=',
						'icon':'images/prettySociable/large_icons/digg.png',
						'sizes':{'width':70,'height':70}
					}
					//add more social networks here
				},
				tooltip: {
						offsetTop:0,
						offsetLeft: 10
					},
				popup: {
					width: 900,
					height: 500
				},
				callback: function(){} /* Called when prettySociable is closed */
			});	

The settings object is self explaining. You can specify which websites to use and also the icons to use for each website in the websites parameter.

You can enhance this drag n share script even further by using a shortened URL in the anchor tag’s href attribute.

P.S.: To get this script to work correctly in IE, you will need to set margin and padding values in the style-sheet for anchor elements which are draggable.

12 Lesser Known But Useful WordPress Hacks

WordPress is not only a great blogging tool but a great content management platform that provides a lot of ways to let you hack into into its functionality to make it do whatever you want. Here are 12 lesser known wordpress hacks/ tricks that you might find useful for your next WordPress related project.

Most of these hacks require your WordPress template to have functions.php file, if it doesn’t exist, create one.

1. Add private notes to your WordPress blog posts

If you would like to add reference notes to your posts that will only be visible to authors of your blog, add this function to your theme’s functions.php file which will create a shortcode [note] so that you can add notes for authors by including them in [note] and [/note] while writing the post.

add_shortcode( 'note', 'sc_note' );
function sc_note( $atts, $content = null ) {
	 if ( current_user_can( 'publish_posts' ) )
		return '<div class="note">'.$content.'</div>';
	return '';
}

2. How to disable HTML in WordPress comments

WordPress allows some HTML tags like <a>, <em>, <strong> within comment text. But if you would like to disable this feature on your blog to prevent users from adding any HTML content within comment text, add this function to your theme’s functions.php file. This will treat the HTML content within comment text as literals and display them as it is.

// This will occur when the comment is posted
function plc_comment_post( $incoming_comment ) {

	// convert everything in a comment to display literally
	$incoming_comment['comment_content'] = htmlspecialchars($incoming_comment['comment_content']);

	// the one exception is single quotes, which cannot be #039; because WordPress marks it as spam
	$incoming_comment['comment_content'] = str_replace( "'", ''', $incoming_comment['comment_content'] );

	return( $incoming_comment );
}

// This will occur before a comment is displayed
function plc_comment_display( $comment_to_display ) {

	// Put the single quotes back in
	$comment_to_display = str_replace( ''', "'", $comment_to_display );

	return $comment_to_display;
}

add_filter( 'preprocess_comment', 'plc_comment_post', '', 1);
add_filter( 'comment_text', 'plc_comment_display', '', 1);
add_filter( 'comment_text_rss', 'plc_comment_display', '', 1);
add_filter( 'comment_excerpt', 'plc_comment_display', '', 1);

Source: How to disable HTML in WordPress Comments

3. Check if a WordPress plugin is active

You might sometime need to check whether a particular plugin is activated or not either to use its functionality or prevent any conflicts from occurring. WordPress provides a function is_plugin_active that accepts path to the plugin file and checks to see if plugin is activated or not.

<?php
if (is_plugin_active('plugin-directory/plugin-file.php')) {
    //plugin is activated
}
?>

Source: Check if a WordPress Plugin is active – WpRecipes

4. Prevent Plugins from automatically loading stylesheets and scripts

Many plugins add their own stylesheets and scripts to your site to perform their function. But if you are using a lot of plugins on your WordPress blog, then this might lead to slow loading of your web pages as lots of scripts and stylesheets will require to be loaded first. What you can do to boost performance of your site while using plugins is combine their CSS and JavaScript files and prevent them to load on their own. For that you’ll need to look into plugin files and find out the handler names of all the CSS and JS files plugins are loading using wp_enqueue_script() and wp_enqueue_style() functions.
For example, if you use wp-pagenavi plugin, it loads its own stylesheet using the function:

wp_enqueue_style('wp-pagenavi', plugins_url('wp-pagenavi/pagenavi-css.css'), false, '2.50', 'all');

The first parameter to wp_enqueue_style() or wp_enqueue_script() is the name of handler for CSS or JS file.
In this case the handler name is wp-pagenavi. Now add these lines to your theme’s functions.php file to prevent it from loading.

//Prevent Stylesheets from loading
add_action( 'wp_print_styles', 'my_deregister_styles', 100 );

function my_deregister_styles() {
	wp_deregister_style( 'wp-pagenavi' );
}

//Prevent JavaScript files from loading automatically
add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 );

function my_deregister_javascript() {
	wp_deregister_script( 'nameofhandler );
}

Source: How to Disable Scripts and Styles – Justin Tadlock

5. Showing Last Modified Date for a post

If you regularly update your old blog posts, then why not show the last modified date on the post page to let readers know when the post was last updated. Use this code to display the last modified date if the post has been modified at a later date.

Posted on <?php the_time('F jS, Y') ?>
<?php $u_time = get_the_time('U');
$u_modified_time = get_the_modified_time('U');
if ($u_modified_time != $u_time) {
echo "and last modified on ";
the_modified_time('F jS, Y');
echo ". "; } ?>

6. Custom Taxonomies in WordPress

By default, WordPress has two taxonomies categories and tags to group posts but custom taxonomies allow you to group your pages in your own custom ways, for example if you are running a movie review blog, you might want to add a taxonomy of genre to group movie review by genre, or a taxonomy of actors to group posts by actors. Custom taxonomies free you from restrictions of categories and tags.

You can add a custom taxonomy by adding this code to your theme’s functions.php file.

add_action( 'init', 'create_my_taxonomies', 0 );

function create_my_taxonomies() {
	register_taxonomy( 'genre', 'post', array( 'hierarchical' => false, 'label' => 'Genre', 'query_var' => true, 'rewrite' => true ) );
	register_taxonomy( 'actors', 'post', array( 'hierarchical' => false, 'label' => 'Actors', 'query_var' => true, 'rewrite' => true ) );
}

This will add new boxes to your add post page in admin panel if you are using WordPress 2.8+ using which you can add values for custom taxonomies. Justin Tadlock has written complete tutorial on how to create and use custom taxonomies, refer to it for more.

7. Create Post Only for your RSS Subscribers

If you would like to give an exclusive offer to your regular RSS subscribers, here’s a nice trick to create a post that is only visible to your RSS subscribers.

First of all, create a category that will hold posts to show to your RSS suscribers. For example, create a category ‘RSS’ and add some posts exclusively to it. Note down the category ID of this category. Now in your theme’s functions.php file, add these lines of code so that it is only shown to RSS subscribers.

<?php
function excludeCategory($query)
{
	if($query->is_home | $query->is_archive )
	//Exclude category from all other pages except RSS
	$query->set('cat','-3');
	return $query;
}
add_filter('pre_get_posts', 'excludeCategory');
?>

8. Get Rid of Curly quotes

WordPress usually replaces pair of double quotes with curly quotes e.g. “something” will become “something”. This is fine for most of the blogs and they look nice too but if you post source code in your posts, then you need to disable this functionality as it’ll also transform quotes within source code. Paste this code into your theme’s functions.php file.

<?php remove_filter('the_content', 'wptexturize'); ?>

Source: Get rid of Curly Quotes in WordPress Blog – WpRecipes

9. Deny Comment Posting to Spammers

You can keep a good number of spam comments away from your blog by checking the referrer URL of the posted comment form. Most of the spam comments are usually made by automated scripts and they just post the data to wp-comments-post.php so that there’s no referral URL through which form is submitted.
You can add a rule to your blog’s .htaccess file so that it restricts the access of wp-comments-post.php to requests that provide referral URL.
Here are the rules you need to add to .htaccess file. Do backup .htaccess file before modifying.

RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*yourblog.com.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]

Source: How To Deny Comment Posting to no referrer requests – WpRecipes

Note: This will only prevent spam bots or automated scripts from posting comment and not those individuals that manually post them. You should use Akismet or other spam preventing tools in addition to this.

10. Insert Ads Within RSS Feed

Here’s a nice hack to add any HTML content into RSS Feeds like ads, copyright info or anything you want to show to just your RSS readers. Add this code to your theme’s functions.php file and you can customize the HTML content to anything you want to append or prepend to posts.

<?php
function insertAds($content) {
    $content = $content.'<hr /><a href="http://webdeveloperplus.com">Visit WebDeveloper Plus for latest Web Design/Development Information</a>';
    return $content;
}
add_filter('the_excerpt_rss', 'insertAds');
add_filter('the_content_rss', 'insertAds');
?>

11. Disable WordPress Feeds

If you are using WordPress as CMS which has just static content, then you might want to disable RSS feeds as it won’t be of any use for your users. Add this code to your functions.php file to disable RSS feeds.

function fb_disable_feed() {
	wp_die( __('No feed available,please visit our <a href="'. get_bloginfo('url') .'">homepage</a>!') );
}
 
add_action('do_feed', 'fb_disable_feed', 1);
add_action('do_feed_rdf', 'fb_disable_feed', 1);
add_action('do_feed_rss', 'fb_disable_feed', 1);
add_action('do_feed_rss2', 'fb_disable_feed', 1);
add_action('do_feed_atom', 'fb_disable_feed', 1);

Source: Disable WordPress Feed – WpEngineer

12. Link Post Title to External URL

If you sometimes share just a link to other article out there which your readers might find useful, then here’s a nice hack to link the title of the post in your main template directly to the external URL. This will save your readers some time as they won’t have to open the post page just to find the resource link. Here’s how to do it:
Add these lines of code to functions.php file.

function print_post_title() {
	global $post;
    $thePostID = $post->ID;
    $post_id = get_post($thePostID);
    $title = $post_id->post_title;
    $perm = get_permalink($post_id);
    $post_keys = array(); $post_val = array();
    $post_keys = get_post_custom_keys($thePostID);

    if (!empty($post_keys)) {
		foreach ($post_keys as $pkey) {
			if ($pkey=='title_url') {
				$post_val = get_post_custom_values($pkey);
			}
		}
		if (empty($post_val)) {
			$link = $perm;
		} else {
			$link = $post_val[0];
		}
    } else {
		$link = $perm;
    }
    echo '<h2><a href="'.$link.'" rel="bookmark" title="'.$title.'">'.$title.'</a></h2>';
}

Next, you need to find out following lines in your theme’s index.php file:

<h2><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h2>

Replace these lines with the following

<?php print_post_title() ?>

Now whenever you want to share an external URL, add a custom field to your post named title_url and set its value as the URL of the resource.
Source: WPBeginner

Create Post Only For Your RSS Subscribers in WordPress

To benefit their regular readers, blog owners some times need to create posts only for those who subscribe to their RSS Feed. The benefit might be some promotional scheme, freebies or discount announcement that you only want to provide to your regular RSS subscribers. Here's how to do it if you have a WordPress powered blog.

1. First of all, you need to define a category specifically for posts that are to be displayed only in RSS Feed. Let’s say you define a new category RSS Only to handle RSS only posts.

After defining the category note down its category ID. To know category ID of the category, open the edit category page for that category and in the address bar of the page, you can find category ID.

2. Now open your theme's functions.php file in an editor or use the theme editor in WordPress admin. If your theme does not have functions.php file, create one. Add the following code to your functions.php file.

<?php
function excludeCategory($query)
{
	if($query->is_home | $query->is_archive )
	$query->set('cat','-3');
	return $query;
}
add_filter('pre_get_posts', 'excludeCategory'); 
?>

pre_get_posts is a WordPress filter which is run before fetching posts from the database. What we've done here is to exclude the category defined above from all pages except RSS Feed. Remember to use the negative sign before category ID to exclude that category.

Now whenever you add a post to this category, it won't show up on your blog's homepage, category page, tag page or any other archive page but will be visible in your RSS Feed exclusively for your RSS subscribers.

The post page would however be there as it is for every other post but the post won't show up anywhere else on your blog.

3. And lastly, if you are using wp_list_categories function to display categories list somewhere in your theme, you need to pass a parameter to wp_list_categories to exclude category meant only for RSS feeds from displaying.

wp_list_categories('exclude=3');

And if wp_list_categories already has parameters then append the exclude parameter using & sign.

wp_list_categories('show_count=1&exclude=3');

Now you can create special posts meant only for your RSS readers. If you know or use some other method of creating RSS only posts, feel free to share them in comments below.

Saving State For Collapsible Drag Drop Panels

I earlier posted about Collapsible Drag and Drop Panels using jQuery where many of you asked about how to save the state of panels and retrieve them when user loads the page again. Here’s the complete solution to that problem using MySQL database to store the state of panels. Also, there were some browser dependent problems which i have tried to remove, let me know if you still encounter any problem implementing.

Creating the Database

The database table widgets consists of 5 columns:

  • id stores the id of panel.
  • column_id is the column number to which panel belongs.
  • sort_no is the order of panel within column.
  • collapsed stores information about whether the panel is collapsed or not.
  • title is the title of the widget.

You can of course add more columns to this database but first four are critical to working of the script. You can add more columns like RSS feed URL that you want to display in that panel or its content etc. To keep things simple and easy to understand, i have skipped that.
Here’s the SQL code:

CREATE TABLE IF NOT EXISTS `widgets` (
  `id` int(11) NOT NULL auto_increment,
  `column_id` int(11) NOT NULL,
  `sort_no` int(11) NOT NULL,
  `collapsed` tinyint(4) NOT NULL,
  `title` varchar(100) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;

--
-- Dumping data for table `widgets`
--

INSERT INTO `widgets` (`id`, `column_id`, `sort_no`, `collapsed`, `title`) VALUES
(1, 2, 0, 1, 'Widget 1'),
(2, 1, 0, 0, 'Widget 2'),
(3, 2, 1, 0, 'Widget 3'),
(4, 2, 2, 0, 'Widget 4'),
(5, 1, 1, 1, 'Widget 5');

As you can see, I have also added some default data to widgets table, but if you are using this in production environment, you will have to create an interface for adding new panels which will add new rows to widgets table.

Displaying Panels Using Database

Since I added some default data to widgets table, here’s how to display the widgets keeping their saved state intact.

Remember to update the Database configuration detail in config.php file.
This code is within index.php file.

<div id="console" ></div>
	
		<?php
		$dummy="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vestibulum velit ultricies orci pharetra elementum. In massa mauris, varius sed tempus a, iaculis sed erat. Ut sollicitudin tellus mollis arcu laoreet semper. Suspendisse ut felis odio. Aliquam auctor, tortor sit amet suscipit elementum, nunc ante dictum lectus, ac accumsan justo nunc sed velit. Sed sollicitudin varius tortor vitae varius..";
		
		include('./config.php');
			
			$columns=mysql_query('SELECT DISTINCT column_id FROM widgets ORDER BY column_id');
			while($column=mysql_fetch_array($columns))
			{
				echo '<div class="column" id="column'.$column['column_id'].'" >';
				$items=mysql_query("SELECT * FROM widgets WHERE column_id='".$column['column_id']."' ORDER BY sort_no");
				while($widget=mysql_fetch_array($items))
				{
					echo '
					<div class="dragbox" id="item'.$widget['id'].'">
						<h2>'.$widget['title'].'</h2>
							<div class="dragbox-content" ';
					if($widget['collapsed']==1)
						echo 'style="display:none;" ';
					echo '>
								'.substr($dummy, 0, rand(120, strlen($dummy))).'
							</div>
					</div>';
				}				
				echo '</div>';
			}
		?>

Explanation First of all, fetch the unique column_id‘s from widgets table and then for each column, their panels in the sort order and then display them.
I’m using a variable $dummy to produce dummy content for widgets.

The JavaScript Code

In earlier article, i wrote about a variable sortorder that was used to pass information to server side script for processing. But it only stored information about order of panels and their column but not the state of each panel i.e. whether panel is collapsed or not was not passed to server side script.

So, I worked out the JavaScript code so that it saves all the information about state of each panel that is its column, its order in the column and its collapse state.
For that I have used an array of JavaScript objects with each object storing information about each panel.

And to pass the array of objects, I used jQuery JSON plugin (mere 2KB) that will make it easy to pass data to server side script in JSON format.

Moreover, since state needs to be saved not only when panels are changed by dragging but also when a panel is collapsed or opened. That is why I created a function updateWidgetData() that will be called whenever the state needs to be saved.

Here’s the JavaScript code, it resides within <head> tag inside index.php file.

$(function(){
	$('.dragbox')
	.each(function(){
		$(this).hover(function(){
			$(this).find('h2').addClass('collapse');
		}, function(){
		$(this).find('h2').removeClass('collapse');
		})
		.find('h2').hover(function(){
			$(this).find('.configure').css('visibility', 'visible');
		}, function(){
			$(this).find('.configure').css('visibility', 'hidden');
		})
		.click(function(){
			$(this).siblings('.dragbox-content').toggle();
			//Save state on change of collapse state of panel
			updateWidgetData();
		})
		.end()
		.find('.configure').css('visibility', 'hidden');
	});
    
	$('.column').sortable({
		connectWith: '.column',
		handle: 'h2',
		cursor: 'move',
		placeholder: 'placeholder',
		forcePlaceholderSize: true,
		opacity: 0.4,
		start: function(event, ui){
			//Firefox, Safari/Chrome fire click event after drag is complete, fix for that
			if($.browser.mozilla || $.browser.safari) 
				$(ui.item).find('.dragbox-content').toggle();
		},
		stop: function(event, ui){
			ui.item.css({'top':'0','left':'0'}); //Opera fix
			if(!$.browser.mozilla && !$.browser.safari)
				updateWidgetData();
		}
	})
	.disableSelection();
});

function updateWidgetData(){
	var items=[];
	$('.column').each(function(){
		var columnId=$(this).attr('id');
		$('.dragbox', this).each(function(i){
			var collapsed=0;
			if($(this).find('.dragbox-content').css('display')=="none")
				collapsed=1;
			//Create Item object for current panel
			var item={
				id: $(this).attr('id'),
				collapsed: collapsed,
				order : i,
				column: columnId
			};
			//Push item object into items array
			items.push(item);
		});
	});
	//Assign items array to sortorder JSON variable
	var sortorder={ items: items };
			
	//Pass sortorder variable to server using ajax to save state
	$.post('updatePanels.php', 'data='+$.toJSON(sortorder), function(response){
		if(response=="success")
			$("#console").html('<div class="success">Saved</div>').hide().fadeIn(1000);
		setTimeout(function(){
			$('#console').fadeOut(1000);
		}, 2000);
	});
}

There were some browser inconsistencies like Firefox/Safari/Chrome fire click event on drag completion while IE/Opera do not fire which leads to inconsistent state which i have fixed as mentioned within the code.

PHP Code To Save State

In the above JavaScript code, I used updatePanels.php in the AJAX call to save state.
Here's the code for updatePanels.php

<?php
if(!$_POST["data"]){
	echo "Invalid data";
	exit;
}
//Include DB config file
include('./config.php');

//decode JSON data received from AJAX POST request
$data=json_decode($_POST["data"]);

foreach($data->items as $item)
{
	//Extract column number for panel
	$col_id=preg_replace('/[^\d\s]/', '', $item->column);
	//Extract id of the panel
	$widget_id=preg_replace('/[^\d\s]/', '', $item->id);
	$sql="UPDATE widgets SET column_id='$col_id', sort_no='".$item->order."', collapsed='".$item->collapsed."' WHERE id='".$widget_id."'";
	mysql_query($sql) or die('Error updating widget DB');
}
echo "success";

?>

The code is pretty self explanatory, just decode the JSON string received from AJAX call and loop through items to save their state to database.

Hopefully this will help solve most of the problems many of you were encountering. Special thanks to Mark Mckee for inspiring me to code the full solution.

AJAX Multiple File Upload Form Using jQuery

Multiple file upload forms are sometimes essential for your web application but managing upload from multiple file input boxes becomes a bit tedious and lengthy. But thanks to jQuery using which we can make this task easier too. Today I’m going to create an AJAXified multiple file upload form that uses a lot lesser server side code and also provides a very nice user interface.

For this tutorial, i’ll be using latest version of jQuery and Ajax upload library by Andrew Valums. Grab both libraries and add them to your page header

The HTML Structure

As i said, the upload form will be intuitive, we won’t be using the classic File input box. So, First of all create the upload button on which user will click to open the File Selection dialog.

<div id="upload" >Upload File</div>

You can use any element you want for the button. I just applied some basic style to this div, you can apply any style you wish to make it look more attractive.

#upload{
	margin:30px 200px; padding:15px;
	font-weight:bold; font-size:1.3em;
	font-family:Arial, Helvetica, sans-serif;
	text-align:center;
	background:#f2f2f2;
	color:#3366cc;
	border:1px solid #ccc;
	width:150px;
	cursor:pointer !important;
	-moz-border-radius:5px; -webkit-border-radius:5px;
}

I also added a span element next to upload button to show various messages during processing. And to show the uploaded files to the user, I added an unordered list next to the button. Here’s the complete html code.

<!-- Upload Button-->
<div id="upload" >Upload File</div><span id="status" ></span>
<!--List Files-->
<ul id="files" ></ul>

The PHP Code

To upload the files to server, here’s a basic file uploading script in PHP that displays ‘success’ if file uploaded successfully otherwise displays ‘error’.

upload-file.php

<?php
$uploaddir = './uploads/'; 
$file = $uploaddir . basename($_FILES['uploadfile']['name']); 
 
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) { 
  echo "success"; 
} else {
	echo "error";
}
?>

The JavaScript Code

And lastly the javascript part. The AJAX Upload library you included earlier will do all the heavy lifting for you. Here’s the JavaScript Code you’ll need.

$(function(){
	var btnUpload=$('#upload');
	var status=$('#status');
	new AjaxUpload(btnUpload, {
		action: 'upload-file.php',
		//Name of the file input box
		name: 'uploadfile',
		onSubmit: function(file, ext){
			if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){ 
                  // check for valid file extension 
				status.text('Only JPG, PNG or GIF files are allowed');
				return false;
			}
			status.text('Uploading...');
		},
		onComplete: function(file, response){
			//On completion clear the status
			status.text('');
			//Add uploaded file to list
			if(response==="success"){
				$('<li></li>').appendTo('#files').html('<img src="./uploads/'+file+'" alt="" /><br />'+file).addClass('success');
			} else{
				$('<li></li>').appendTo('#files').text(file).addClass('error');
			}
		}
	});
});

Code explanation: to use the AJAX Upload library we need to initialize the AjaxUpload object and provide it with parameters. The first parameter is the id of the button element on which the user will click and second is the server side script that’ll handle file upload. The second parameter can accept an array of various options to give you more control over the process.

And that’s exactly what i’ve done.

  • The action field is the path to server side script,
  • name is the name of file input box(hidden) which will be used for upload. If you change this value, make sure to change the server side script corresspondinly.
  • onSubmit lets you perform some function before the file is uploaded e.g. you can check the file extension like i’ve done above or show a status message.
  • onComplete lets you perform some action after the upload is complete e.g. I’ve shown the uploaded image to the user.

And if you want to limit the number of files that a user can upload at a time, simply use this.disable() within onSubmit or onComplete to disable the upload button after checking for some condition.

Note: The file upload using AJAX is not true ajax as it uses hidden iframe to upload the form data but his whole process is transparent by using the AJAX Upload library and gives a feel of AJAXified file upload.