Top WordPress hacks of early 2010

Top WordPress hacks of early 2010

Display an incrementing number on each post

I always loved how A List Apart numbers its posts. The following hack will let you do the same with your own blog, using a custom field.

Implementing this hack is quite simple. First, paste the following function into your functions.php file:

function updateNumbers() {
  global $wpdb;
  $querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' ";
$pageposts = $wpdb->get_results($querystr, OBJECT);
  $counts = 0 ;
  if ($pageposts):
    foreach ($pageposts as $post):
      setup_postdata($post);
      $counts++;
      add_post_meta($post->ID, 'incr_number', $counts, true);
      update_post_meta($post->ID, 'incr_number', $counts);
    endforeach;
  endif;
}  

add_action ( 'publish_post', 'updateNumbers' );
add_action ( 'deleted_post', 'updateNumbers' );
add_action ( 'edit_post', 'updateNumbers' );

Once done, you can display the post number with the following code. Note that it have to be used within the loop.

<?php echo get_post_meta($post->ID,'incr_number',true); ?>

Source: http://www.wprecipes.com/how-to-display-an-incrementing-number-next-to-each-published-post

Allow your contributors to upload files

If you’re like me, you have guest contributing articles on your blog and you might be annoyed that the contributor role doesn’t allow file uploads. Most blog posts need images to stand out of the crowd so
this hack is extremely handy: Just paste it on your function.php file and your contributors will be allowed to upload files in the WordPress dashboard. How cool is that?

if ( current_user_can('contributor') && !current_user_can('upload_files') )
    add_action('admin_init', 'allow_contributor_uploads');

function allow_contributor_uploads() {
    $contributor = get_role('contributor');
    $contributor->add_cap('upload_files');
}

Source: http://www.wprecipes.com/wordpress-tip-allow-contributors-to-upload-files

Display “time ago” dates

Twitter has a very cool function which displays the elapsed time since a tweet has been published. What about doing the same with WordPress? Of course it’s possible!
This code just needs to be pasted in your functions.php file. Once you saved the file, posts that were published less than 24 hours ago will display “Published XX ago” instead of regular dates.

add_filter('the_time', 'timeago');

function timeago() {
    global $post;
    $date = $post->post_date;
    $time = get_post_time('G', true, $post);
    $time_diff = time() - $time;
    if ( $time_diff > 0 && $time_diff < 24*60*60 )
        $display = sprintf( __('%s ago'), human_time_diff( $time ) );
    else
        $display = date(get_option('date_format'), strtotime($date) );

    return $display;
}

By the way, if you’re on Twitter do not hesitate to follow me!
Source: http://aext.net/2010/04/display-timeago-for-wordpress-if-less-than-24-hours/

WordPress navigation outside the loop

WordPress provides some functions which allow you to link to the next and previous posts. However, those functions have to be used within the loop. Jeff Starr, who wrote the Digging into WordPress book, has the solution to this problem.
Simply paste the code below on your single.php file, where you’d like to link to the next and previous posts. Or even better, put the code in a php file and then include it in your theme file.

<?php if(is_single()) { // single-view navigation ?>
	<?php $posts = query_posts($query_string); if (have_posts()) : while (have_posts()) : the_post(); ?>
		<?php previous_post_link(); ?> | <?php next_post_link(); ?>
	<?php endwhile; endif; ?>
<?php } else { // archive view navigation ?>
		<?php posts_nav_link(); ?>
<?php } ?>

Source: http://digwp.com/2010/04/post-navigation-outside-loop/

Disallow theme switching

If you’re like me, you’ve created WordPress themes for your clients and already face a problem: The client “explored” the WordPress dashboard and “accidentally” switched the theme.
Using WordPress actions, we can easily remove the “themes” menu and consequently prevent the risk of having a client switching the theme. The code below just has to be pasted in your functions.php. The “themes” menu will be removed once the file is saved.

add_action('admin_init', 'remove_theme_menus');
function remove_theme_menus() {
	global $submenu;	

	unset($submenu['themes.php'][5]);
	unset($submenu['themes.php'][15]);
}

Source: http://soulsizzle.com/quick-tips/stopping-clients-from-switching-their-wordpress-theme/

Get rid of unused shortcodes in your posts

WordPress shortcodes are extremely useful, but they have a weak point: If you use a shortcode in your posts and then stop to use it for some reason, the shortcode code (Like [shortcode] for example) will stay in your posts.

To get rid of unused shortcodes, you just have to execute this line of SQL code. This can be done using PhpMyAdmin or the SQL command line interpreter. Don’t forget to replace [tweet] by the unused shortcode you’d like to delete from your posts.

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

Source: http://www.wprecipes.com/wordpress-tip-get-rid-of-unused-shortcodes

Switch WordPress theme programmatically

Recently, I worked on an interesting project where I had to switch the blog theme automatically. As the current WordPress theme name is saved in the wp_options table of your WordPress database, we can easily change it.
The cleanest way to do it is definitely to use the update_option() function, as shown in the function below. Paste it in your functions.php file.

function updateTheme($theme){
    update_option('template', $theme);
    update_option('stylesheet', $theme);
    update_option('current_theme', $theme);
}

Once you’ve added the function to your functions.php file, you can call it wherever you need it:

<php updateTheme('default'); ?>

Modify WordPress dashboard footer text

Another good tip for those who create WordPress themes for clients is to modify the WordPress dashboard footer text, and add (for example) a link to your support forum. The only thing you have to do is to copy this code and paste it in functions.php:

function remove_footer_admin () {
    echo "Your own text";
} 

add_filter('admin_footer_text', 'remove_footer_admin');

Source: http://www.wprecipes.com/wordpress-tip-how-to-change-the-dashboard-footer-text

Programmatically Creating Posts in WordPress

If for some reason you need to programmatically insert posts in WordPress database, you’ll be amazed to see how easy is it. The wp_insert_post() takes an array of data as a parameter, and then return the post ID.

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

Source: http://www.webmaster-source.com/2010/02/09/programmatically-creating-posts-in-wordpress

WordPress 3.0: Query custom post types

WordPress 3.0 should be released soon. And I don’t know about you, but personally, I can’t wait. Lots of exiting features are scheduled. One of them is particularly interesting in my opinion: the custom post types, which allow you to define a custom type for a post.
In order to be able to retrieve posts of a specific type from a WordPress database, you can use the following loop, which will get the albums post type:

<ul>
<?php global $wp_query;
$wp_query = new WP_Query("post_type=albums&post_status=publish");

while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>

</ul>

Source: http://www.catswhocode.com/blog/8-useful-code-snippets-to-get-started-with-wordpress-3-0

Please note that I’m currently accepting freelance work; so if you need any kind of WordPress help, I’ll be happy to help you. Simply send me an email and I’ll get back to you.

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

Top WordPress hacks of early 2010

Manipulating the DOM with jQuery: 10+ useful code snippets

Manipulating the DOM with jQuery: 10+ useful code snippets

Add a CSS class to a specific element

A very clean way to change an element look and feel is to add a css class, instead of adding inline styles. Using jQuery, this is pretty easy to do:

$('#myelement').addClass('myclass');

Removing a CSS class from a specific element

It’s great to be able to add some CSS classes, but we also need to know how to remove unwanted classes. The following line of code will do that:

$('#myelement').removeClass('myclass');

Check if a specific element has a CSS class

If your application or site is frequently adding and removing classes to a particular element, it can be very useful to be able to check out if an element has a certain CSS class.

$(id).hasClass(class)

Switch CSS using jQuery

As we saw with the previous examples, adding or removing css styles to an element is very simple using jQuery. But what if you want to completely remove the document css file and attach a new stylesheet? Good news, it is extremely simple as well, as shown in the following example:

$('link[media='screen']').attr('href', 'Alternative.css');

Source: http://addyosmani.com/blog/50-jquery-snippets-for-developers/

Append HTML to an element

When you need to append some html to an element, the append() method is a life saver:

$('#lal').append('sometext');

Check if an element exists

When working with Javascript, we often need to check if an element exists or not. Using jQuery and the length property, it is very simple to do: If length == 0, no elements are used on the page. Otherwise, some are used.

if ($('img').length) {
    log('We found img elements on the page using "img"');
} else {
    log('No img elements found');
}

Source: http://jqueryfordesigners.com/element-exists/

Get the parent element of an element

When working with the DOM, you may need to know which element is the direct parent of another element. The closest() method will let you know:

var id = $("button").closest("div").attr("id");

Source: http://stackoverflow.com/questions/545978/finding-the-id-of-a-parent-div-using-jquery

Get element siblings

The siblings() method is a very handy tool to get siblings of an element. As shown below, using this method is extremely simple:

$("div").siblings()

Remove an option from a select list

When working with select lists, you may want to update the content according to the user actions. To remove an option from a select list, the following code will do the trick:

$("#selectList option[value='2']").remove();

Source: http://calisza.wordpress.com/2009/03/29/6-jquery-snippets-you-can-use-to-manipulate-select-inputs/

Get the selected option as text

Extremely useful when you need to quickly check out what a visitor selected from your select list.

$('#selectList :selected').text();

Apply a “zebra” effect on tables

When using tables, it is a good idea, for better readability, to give a different style to one line out of two. Using jQuery, this can be done easily, without any additional html markup.

$("tr:odd").addClass("odd");

Source: http://web.enavu.com/tutorials/top-10-jquery-snippets-including-jquery-1-4/

Count children of an element

If you’d like to count how many div elements are children of #foo, the following line will let you know. Simple and efficient!

$("#foo > div").length

Source: http://tympanus.net/codrops/2010/01/05/some-useful-javascript-jquery-snippets/

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

Manipulating the DOM with jQuery: 10+ useful code snippets

WordPress tip: Insert custom content after each post

WordPress tip: Insert custom content after each post

You just have to paste the following code into your functions.php and save the file. Once done, custom content will be inserted below each of your posts.

function add_post_content($content) {
	if(!is_feed() && !is_home()) {
		$content .= '<p>This article is copyright &copy; '.date('Y').'&nbsp;'.bloginfo('name').'</p>';
	}
	return $content;
}
add_filter('the_content', 'add_post_content');

Thanks to Jeff Starr for the great snippet!

By the way, if you need any kind of WordPress help I’m happy to inform you that I’m starting to work freelance. Don’t hesitate to contact me to get a quote for your new project!

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

WordPress tip: Insert custom content after each post

How to display Twitter-like “time ago” on your WordPress blog

How to display Twitter-like “time ago” on your WordPress blog

The first thing to do is to create the function. To do so, paste the following into your functions.php file:

function time_ago( $type = 'post' ) {
	$d = 'comment' == $type ? 'get_comment_time' : 'get_post_time';
	return human_time_diff($d('U'), current_time('timestamp')) . " " . __('ago');
}

Once done, you can use the function in your theme files:

<?php echo time_ago(); ?>

Thanks to UpThemes for this trick!

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

How to display Twitter-like “time ago” on your WordPress blog

8 useful code snippets to get started with WordPress 3.0

8 useful code snippets to get started with WordPress 3.0

How to create a custom post type

Custom post type are an incredible step forward for WordPress, because it will allow developers to create post types according to their needs.
For now, we have posts, and pages. With WordPress 3.0, we’ll be able to create a new post type called products, where a client can sell his products only, while regular post for his blog.

Creating a custom post type is easy: All you have to do is to open your theme functions.php file and paste the following:

$args = array(
        'label' => __('Products'),
        'singular_label' => __('Product'),
        'public' => true,
        'show_ui' => true,
        'capability_type' => 'page',
        'hierarchical' => false,
        'rewrite' => true,
        'query_var' => 'products',
        'supports' => array('title', 'thumbnail')
);
register_post_type( 'album' , $args );

Once you saved the file, login to your WordPress dashboard and have a look at the navigation on the left: A new post type, named Products, has been added.
Source: http://codex.wordpress.org/Function_Reference/register_post_type

Custom post types with custom taxonomies

In the previous example, I’ve shown you how to create a custom post type, which is pretty useful to use WordPress as a real CMS and not a simple blog publishing platform.

Now, let’s see something a little bit more complex, but extremely interesting: Creating a custom post type associated with custom taxonomies. For those who don’t know, a taxonomy is a term (such as category, tag or anything else) related to posts. For more information about taxonomies, you should have a look at WordPress Codex.

In this example, we’ll create a custom post type named Albums, which belong to “Genres” (the custom categories) and have “Performer” as tags. This snippet has to be pasted in your functions.php file. With those 27 lines of codes, you can create a fully functional music albums archive. Ain’t that powerful?

function post_type_albums() {
	register_post_type(
                     'albums',
                     array('label' => __('Albums'),
                             'public' => true,
                             'show_ui' => true,
                             'supports' => array(
                                        'post-thumbnails',
                                        'excerpts',
                                        'trackbacks',
                                        'comments')
                                )
                      );
// Adding the Custom Taxonomy for Genres. Here we can create categories specific for this post type.
	register_taxonomy( 'genres', 'albums', array( 'hierarchical' => true, 'label' => __('Genres') ) );

// Adding the Custom Taxonomy for Performer. Here we can add tags specific for this post type.
        register_taxonomy( 'performer', 'albums',
		array(
                         'hierarchical' => false,
			 'label' => __('Performer'),
			 'query_var' => 'performer',
			 'rewrite' => array('slug' => 'performer' )
		)
	);
}
add_action('init', 'post_type_albums');

Source: http://wpspecial.net/2010/03/how-to-add-custom-post-types-in-wordpress/

Query custom post types

Now that you’ve learned how to create custom post types, the next step is to learn how to retrieve them from the WordPress database and display it on your blog.

Good news for developers, there’s nothing hard or new in the process. Custom post types can be retrieved easily, using the WP_Query object.
The following example will create a custom loop which will get only the albums custom post type.

<ul>

<?php global $wp_query;
$wp_query = new WP_Query("post_type=albums&post_status=publish");

while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

Source:

Enable multisite feature

One of the most exiting new feature of WordPress 3.0 is definitely multisite management. In brief, with a single installation of WordPress you’ll be able to run a network of WordPress blog. How cool is that?

To take advantage of this feature, simply paste the following line of code in your wp-config.php file. This file is located at the root of your WordPress install.

define('WP_ALLOW_MULTISITE', true);

Source: http://wptheming.com/2010/03/wordpress-3-0-enable-network/

Custom author profiles

Most of the top blogs of the industry do not have a single author but a team of different contributors. WordPress allows you to create author pages, but WordPress 3.0 is introducing a new function which will allow you to use different templates for different authors, like we can currently do with categories.

All you have to do is to create an author page named author-XX.php where XX is either the author ID or nicename. For example, if your user nicename is “john”, you’ll have to call the file author-john.php.

Source: http://codex.wordpress.org/Function_Reference/get_author_template

Add custom backgrounds

WordPress 3.0 is introducing a new feature that will for sure be loved by non tech-friendly users: Custom background. The feature allows the user to upload a background in his WordPress dashboard, specify its position, and automatically have it added to his blog.

Of course, the theme used by the blogger has to support this feature, otherwise the uploaded background will not be visible. To do so, simply open your functions.php file and paste the following line:

add_custom_background();

Style WordPress editor using CSS

WordPress features a WYSIWYG editor, which allow you to see text in bold, italic, and so on. But some people want more, such as being able to visualize their blog post in the blog font and colors.

This new feature allows you to create a css file (named editor-style.css in the example below) and link it to the editor for a better WYSIWYG rendering. Simply paste this code snippet to your functions.php file.

add_filter('mce_css', 'my_editor_style');
function my_editor_style($url) {
  if ( !empty($url) )
    $url .= ',';
  // Change the path here if using sub-directory
  $url .= trailingslashit( get_stylesheet_directory_uri() ) . 'editor-style.css';

  return $url;
}

Source: http://azaozz.wordpress.com/2010/01/02/can-themes-style-the-visual-editor/

Make your theme compatible with WordPress 3.0 menus

WordPress 3.0 is going to feature a totally new menu system, which will allow users to add only the desired pages, add categories, and more. Good news for theme developers; adding WP 3.0 menu support to your themes is extremely easy.

To do so, open functions.php and add the following line:

add_theme_support( 'nav-menus' );

Once added, you can use the brand new wp_nav_menu() function in your theme files:

wp_nav_menu('sort_column=menu_order&container_class=navigation');

As you can see, it accepts the same kind of parameters than the good ol’ wp_list_categories() function.
Source: http://wpspecial.net/2010/04/menu-support-for-wordpress-3-0-themes/

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

8 useful code snippets to get started with WordPress 3.0

WordPress tip: Allow contributors to upload files

WordPress tip: Allow contributors to upload files

Nothng hard with this code: The only thing you have to do is to paste it in your functions.php file:

if ( current_user_can('contributor') && !current_user_can('upload_files') )
    add_action('admin_init', 'allow_contributor_uploads');

function allow_contributor_uploads() {
    $contributor = get_role('contributor');
    $contributor->add_cap('upload_files');
}

Big thanks to Altaf Sayani for his contribution to WpRecipes!

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

WordPress tip: Allow contributors to upload files

Best practices for WordPress coding

Best practices for WordPress coding

Think International

When coding a WordPress theme or plugin, you have to think about those that doesn’t speak English. Using the PHP language, two very useful functions are available for you to create a translatable theme or plugin:

The first is the function _e(), which prints on screen the desired text, translated into the user language:

_e("Text to translate", "textdomain");

The second is __() wich is basically the same than _e(), but returns the text:

function say_something() {
    return __("Text to translate", "textdomain");
}

By using those functions, you make your work translatable in any language, which is a very great thing for people that blog in another language than English.

Additional resources:

Don’t reinvent the wheel: Use a framework

While many people thinks that a good developer is someone that can create quality code, they’re wrong: A good developer is a person who can write quality code, quickly. Being fast is a quality, because clients don’t want to wait, and time is money.

Being fast doesn’t mean writing crappy, untested code in order to get things done as soon as possible. Instead, being fast is all about not wasting time. In development, the most important waste of time someone can do is when you’re reinventing the wheel, i.e. recreating something instead of using the original.

Theme frameworks appeared in 2008. A theme framework is a WordPress theme which can be extended by a child theme. While there are many available frameworks, both free and premium, my favorite is definitely Thematic. You have to learn how Thematic works, which can take some time at first, but once done, you’ll be surprised by how fast you can create robust and optimized themes.

And for those who think that a framework doesn’t allow enough modifications to create any type of layout, you’re wrong: This site and CatsWhoBlog are both using Thematic.

Additional resources:

Speed up development using community tools and templates

As a WordPress developer, most client requests I got were similar: They wanted a custom theme or plugin. The process of creating files and fill it with the required info (Such as plugin name, url, etc) is very simple but time consuming.

For this reason, you should definitely make use of what the community created for you: Themes and plugins templates, as well as a really interesting plugin called WP Dummy Content, which can automatically generate a bunch of pages, sub-pages, posts, etc for you to test the look and feel of the theme you’re building.

Resources

  • The WordPress Starter Theme Project: A very useful set of files containing a blank style.css with theme name, author, URL, etc. tags at the top, a content-ready 404, archive, search, index, single post, and page files, a full, working comments.php file, a complete header.php set up with links to RSS, a stylesheet, and JS file and all you need to start developing a new WordPress theme.
  • WP Dummy Content: a WordPress plugin that will generate a bunch of pages, sub-pages and posts which you specify. Titles and content are automatically generated for you as well, and you have a few choices as to the type and length of content.

Debug your code efficiently

As a developer, debugging code is something that you should be used to. Although debugging is rarely a bunch of fun, WordPress has some useful functions that will definitely make your life easier.

The WP_DEBUG constant has to be placed in your wp-config.php file. If defined and set to true, error messages will be displayed.

define('WP_DEBUG', true);

If you’d like to modify WordPress built-in Javascript, you can enable debugging by defining the SCRIPT_DEBUG constant.

define('SCRIPT_DEBUG', true);

Additional resources

  • WordPress debug techniques: An interesting guide for those who don’t want to spend hours debugging their code.
  • Debug Theme, by Joost: The “Debug Theme” is a very special WordPress theme: instead of making your blog looking good, its purpose is to display useful information such as WordPress constants, security key-phrases, etc. A very handy tool when it comes to debugging!
  • Theme Tester plugin: If you need to modify or create a new theme on a production site, this is a must have: This plugin allows you to show the regular theme to your visitors while you’re working on a new one.

Make use of hooks, actions and filters

WordPress has very interesting an useful features called actions and filters. While those are intensively used by Theme frameworks and some plugins, most newcomer’s in WordPress development are ignoring them.

Actions and filters allow you to modify, overwrite or surcharge an existing WordPress function, without having to edit the core files. For that reason, you should always make sure that both the wp_head() and wp_footer() functions have been implemented in the theme you coded:

<?php wp_head(); ?&gt
    ....
<?php wp_footer(); ?&gt

Using hooks, you can for example add a favicon to your theme without editing the header.php file. The following example is what I use to add a favicon to a Thematic child theme.

function add_favicon() { ?>
    <link rel="shortcut icon" href="<?php echo bloginfo('stylesheet_directory') ?>/images/favicon.png"/>
<?php }
add_action('wp_head', 'add_favicon');

Additional resources

Code markup like a pro

A very important aspect of the quality of a WordPress theme is definitely how it is coded. In fact, I know many developers which are very good in PHP and other back-end technologies, but suck at front-end coding.
WordPress is XHTML valid and standard-compliant, so always make sure that your theme or plugin is as well before selling it to your client.

The idea of “pro front-end coding” is quite subjective, because not everyone has the same quality standards. However, any WordPress theme or plugin should be:

  • XHTML valid: Although their usefulness is often discussed, in clients eyes, respect of web standards makes the difference between a poorly skilled amateur and a professional web developer.
  • Semantically coded: When html tags are used semantically, this is not only the proper way to create a html document, it will also allow your client to get better search engine optimization results.
  • No inline styles or Javascript actions: In-line styles always seem extremely useful at first, but when you have to modify someone else’s work and it’s filled with in-line styles, it quickly become a nightmare. Same goes for javascript actions, such as onmouseover and so on. Always put them in a separate file.

To learn more about front-end coding best practices, you should definitely have a look to my recent “Top 10 best practices for front-end web developers” article.

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

Best practices for WordPress coding

How to display an incrementing number next to each published post

How to display an incrementing number next to each published post

The first thing to do is to paste the function into your functions.php file:

function updateNumbers() {
  global $wpdb;
  $querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' ";
$pageposts = $wpdb->get_results($querystr, OBJECT);
  $counts = 0 ;
  if ($pageposts):
    foreach ($pageposts as $post):
      setup_postdata($post);
      $counts++;
      add_post_meta($post->ID, 'incr_number', $counts, true);
      update_post_meta($post->ID, 'incr_number', $counts);
    endforeach;
  endif;
}  

add_action ( 'publish_post', 'updateNumbers' );
add_action ( 'deleted_post', 'updateNumbers' );
add_action ( 'edit_post', 'updateNumbers' );

Once done, you can display the post nimber by pasting the following on your theme file, within the loop:

<?php echo get_post_meta($post->ID,'incr_number',true); ?> 

Credits goes to WordPress forums for this very cool piece of code!

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

How to display an incrementing number next to each published post

10+ regular expressions for efficient web development

10+ regular expressions for efficient web development

Validate an URL

Is a particular url valid? The following regexp will let you know.

/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \?=.-]*)*\/?$/

Source: http://snipplr.com/view/19502/validate-a-url/

Validate US phone number

This regexp will verify that a US phone number is valid.

/^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/

Source: http://snippets.dzone.com/posts/show/597

Test if a password is strong

Weak passwords are one of the quickest ways to get hacked. The following regexp will make sure that:

  • Passwords will contain at least (1) upper case letter
  • Passwords will contain at least (1) lower case letter
  • Passwords will contain at least (1) number or special character
  • Passwords will contain at least (8) characters in length
  • Password maximum length should not be arbitrarily limited
(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$

Source: http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=297

Get code within <?php and ?>

If for some reason you need to grab all the code contained within the <?php and ?> tags, this regexp will do the job:

<\?[php]*([^\?>]*)\?>

Source: http://snipplr.com/view/12845/get-all-the-php-code-between/

Match tel: urls

In a recent post, I showed you how you can use iPhone special link prfixes to automatically call someone.
This regular expression will match those tel: urls.

^tel:((?:\+[\d().-]*\d[\d().-]*|[0-9A-F*#().-]*[0-9A-F*#][0-9A-F*#().-]*(?:;[a-z\d-]+(?:=(?:[a-z\d\[\]\/:&+$_!~*'().-]|%[\dA-F]{2})+)?)*;phone-context=(?:\+[\d().-]*\d[\d().-]*|(?:[a-z0-9]\.|[a-z0-9][a-z0-9-]*[a-z0-9]\.)*(?:[a-z]|[a-z][a-z0-9-]*[a-z0-9])))(?:;[a-z\d-]+(?:=(?:[a-z\d\[\]\/:&+$_!~*'().-]|%[\dA-F]{2})+)?)*(?:,(?:\+[\d().-]*\d[\d().-]*|[0-9A-F*#().-]*[0-9A-F*#][0-9A-F*#().-]*(?:;[a-z\d-]+(?:=(?:[a-z\d\[\]\/:&+$_!~*'().-]|%[\dA-F]{2})+)?)*;phone-context=\+[\d().-]*\d[\d().-]*)(?:;[a-z\d-]+(?:=(?:[a-z\d\[\]\/:&+$_!~*'().-]|%[\dA-F]{2})+)?)*)*)$

Source: http://tools.ietf.org/html/rfc3966#section-3

Validate US zip code

When building a registration form, it is common to ask the user’s zip code. As forms are often boring, there’s a strong chance that the user will try to register false data. This regular expression will make sure he entered a valid American zip code.

^[0-9]{5}(-[0-9]{4})?$

Source: http://reusablecode.blogspot.com/2008/08/isvalidzipcode.html

Validate Canadian postal code

This regexp is very similar to the previous one, but it will match Canadian postal codes instead.

^[ABCEGHJ-NPRSTVXY]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$

Source: http://reusablecode.blogspot.com/2008/08/isvalidpostalcode.html

Grab unclosed img tags

As you probably know, the xhtml standard requires all tags to be properly closed. This regular expression will search for unclosed img tags. It could be easily modified to grab any other unclosed html tags.

<img([^>]+)(\s*[^\/])>

Source: http://snipplr.com/view/6632/grab-any-unclosed-xhtml-img-tags/

Find all CSS attributes

This regexp will find CSS attributes, such as background:red; or padding-left:25px;.

\s(?[a-zA-Z-]+)\s[:]{1}\s*(?[a-zA-Z0-9\s.#]+)[;]{1}

Source: http://snipplr.com/view/17903/find-css-attributes/

Validate an IBAN

I have recently worked on a banking application and this one was definitely a life-saver. It will verify that the given IBAN is valid.

[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}

Source: http://snipplr.com/view/15322/iban-regex-all-ibans/

Validate a BIC code

Another one very useful for any banking application or website: This regexp will validate a BIC code.

([a-zA-Z]{4}[a-zA-Z]{2}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?)

Source: http://snipplr.com/view/15320/bic-bank-identifier-code-regex/

If you’re interested in regular expressions, make sure you have read our “15 PHP regular expression for developers” post.

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

10+ regular expressions for efficient web development

Automatically replace content in PRE tags by HTML Entities

Automatically replace content in PRE tags by HTML Entities

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

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

Credits goes to David Walsh for this very cool tip!

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

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

Automatically replace content in PRE tags by HTML Entities

Best WordPress Plugins By Category

Premium WordPress Plugins by category

– Advertising –

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

– Affiliates –

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

– SEO –

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

– Websites –

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

Free WordPress Plugins

– Admin Tools –

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

– Advertising –

– Authors –

– Comments –

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

– Domaining –

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

– Downloads –

– Feeds –

– Forums –

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

– Maintenance –

– Miscellaneous –

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

– Related Posts –

– SEO –

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

– Tags –

– Video –

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

WordPress hack: Show your top contributors without a plugin

WordPress hack: Show your top contributors without a plugin

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

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

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

}
echo "</ul>";

?>

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

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

WordPress hack: Show your top contributors without a plugin

WordPress tip: allow upload of more file types

WordPress tip: allow upload of more file types

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

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

    return $mimes;
}
?>

add_filter('upload_mimes', 'addUploadMimes');

Thanks to Pioupioum for this great piece of code!

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

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

WordPress tip: allow upload of more file types

10 examples of futuristic CSS3 techniques

10 examples of futuristic CSS3 techniques

Pure CSS speech bubbles

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

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

Super Awesome Buttons with CSS3 and RGBA

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

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

Classy photo frame using CSS3

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


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

Easily Turn Your Images Into Polaroids with CSS3

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

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

Fancy web form with field hints using only CSS3

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

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

CSS3 Drop down Menu

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

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

CSS 3 selectors explained

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

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

Recreate Mac OSX interface using CSS3

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

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

Letterpress Text Effect Using Photoshop and CSS

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

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

Creating a Polaroid photo viewer with CSS3 and jQuery

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

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

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

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

10 examples of futuristic CSS3 techniques

Protect your website from attacks, A htaccess trick

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

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

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

Follow these steps.

Step1.

Know your IP

Goto
http://www.whatismyip.com

and find your IP address

ie. we get our IP
Lets say

175.189.95.239
Step 2.

Protecting your admin directory

in most of the scripts you find your admin directory are

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

Please Locate your admin directory

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

Now

Step3:

We are protecting our admin directory from attackers.

Now in

yoursite.com/wp-admin

find .htaccess and open it with text-editor

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

add this code to your .htaccess


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

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

add this code to your .htaccess

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

Going to prevent others to enter your site.
🙂