WordPress tip: Automatically empty Trash

Simply open your wp-config.php file (located at the root of your WOrdPress install) and paste the following code:

define('EMPTY_TRASH_DAYS', 10 );

The second parameter is when to empty trash, in days.

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

WordPress tip: Automatically empty Trash

Thematic WordPress Theme Toolbox: 10 extremely useful hooks

If you’re looking for a tutorial on how to create a Thematic child theme, you should read this post.

Add a favicon

A favicon is a small image displayed by modern web browsers. It is a must have for all websites, because it allows your visitors to quickly visualize your site among others when they have lots of browser tabs open at the same time.
This handy code will add your favicon to your theme. Make sure a favicon.png file is in your child theme images directory, and then paste the code in your functions.php file:

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

Source:

Add an Internet Explorer specific stylesheet

Who doesn’t hate Internet Explorer? Unfortunately, most clients will require developers to make their site IE-compliant. And the best way to do so is to use some conditional comments and a dedicated stylesheet.
Create a file named ie.css in your child theme directory, and then insert the following code in your functions.php file:

function childtheme_ie_style() { ?>
	<!--[if IE]>
		<link rel="stylesheet" type="text/css" href="http://www.webdevcat.com/wp-content/themes/webdevcat/ie.css" />
	<![endif]-->
<?php }
add_action('wp_head', 'childtheme_ie_style');

Modify Doctype

By default, Thematic outputs a XHTML 1.0 transitional doctype. If for some reason, you prefer using another kind of doctype, pasting the code below in your functions.php will do the trick.

function childtheme_create_doctype($content) {
 $content = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
 $content .= "\n";
 $content .= '<html xmlns="http://www.w3.org/1999/xhtml"';
 return $content;
}
add_filter('thematic_create_doctype', 'childtheme_create_doctype');

Use Feedburner RSS feeds

Feedburner is very popular among bloggers. If you want to replace default rss feeds by feedburner feeds in Thematic, this code is for you.

function childtheme_rssfeeds($content) {
	$content = "\t";
	$content .= "<link rel=\"alternate\" type=\"application/rss+xml\" href=\"";
	$content .= "http://feeds2.feedburner.com/Catswhocode";
	$content .= "\" title=\"";
	$content .= wp_specialchars(get_bloginfo('name'), 1);
	$content .= " " . __('RSS feed', 'thematic');
	$content .= "\" />";
	$content .= "\n";
	return $content;
}
add_filter('thematic_rss', 'childtheme_rssfeeds');

Add Google Analytics code to your Thematic child theme

Google Analytics is another free and very useful service. In order to allow GA to collect your visitor information and create your stats, you have to insert a small piece of Javascript on your footer.php file.
Insert this code in your functions.php file, save it, and you’re done. Of course, don’t forget to replace the Google Analytics code with your own!

function ga(){ ?>
	<script type="text/javascript">
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
	</script>
	<script type="text/javascript">
	try {
	var pageTracker = _gat._getTracker("UA-XXXXX-10");
	pageTracker._trackPageview();
	} catch(err) {}</script>
<?php }
add_action('wp_footer', 'ga');

Modify Thematic footer credit

If you’re building a Thematic child theme for a client, you may want to insert your credit link in the footer text. The following code will do it. Don’t forget to give credit to Ian Stewart for his awesome work on the Thematic theme framework!

function my_footer($thm_footertext) {
	$thm_footertext = 'Copyright &copy; 2010 Jean-Baptiste Jung. <a href="http://www.webdevcat.com">WebDevCat.com</a> is obviously powered by <a href="http://www.wordpress.org">WordPress</a> &amp; the <a href="http://www.themeshaper.com/thematic">Thematic Theme framework</a>.';
	return $thm_footertext;
}
add_filter('thematic_footertext', 'my_footer');

Display Thematic menu above header

Want to have your navigation menu above your site header? That’s not a problem. This code will remove the menu from below the header and then put it above it.

function remove_thematic_actions() {
    remove_action('thematic_header','thematic_access',9);
    add_action('thematic_aboveheader','search_access',9);
}
add_action('wp','remove_thematic_actions');

Change “more” link text

Thematic “Read More” link displays Read More » by default. The following code allow you to change the “Read More” text.

function childtheme_more_text($content) {
	$content = 'Click to read the rest!';
	return $content;
}
add_filter('more_text', 'childtheme_more_text');

Change gravatar size in Thematic comments

By default, Thematic displays 35px*35px gravatars. If you want to change this size, no problem: Just paste this code in, as usual, your beloved functions.php file.

function childtheme_avatarsize() {
    return '56';
}
add_action( 'avatar_size', 'childtheme_avatarsize' );

Source: http://themeshaper.com/forums/topic/on-using-avatars-in-thematic

Remove Thematic menu on specific page template

If you want to make a squeeze page on your site or blog using Thematic, that’s quite easy: You only have to create a page template and remove the menu. To do so, just paste the code below in your functions.php file.
Don’t forget to set your page template name on line 2.

function remove_access() {
    if (is_page_template('affiliate.php')) {
        remove_action('thematic_header','thematic_access',9);
    }

add_action('wp_head','remove_access');
}

Source: http://themeshaper.com/forums/topic/conditionally-removing-thematic_access

By the way, if you’re interested in Thematic Theme help, don’t hesitate to ask me. I just started freelancing and I’m ready to help you for a reasonable price.

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

Thematic WordPress Theme Toolbox: 10 extremely useful hooks

WordPress hack: Insert comments programatically

The following code can be pasted anywhere on your theme files.
Once this code is executed, it will add a new comment into WordPress database. The returned value is the comment ID, or 0 if a problem happenned.

$data = array(
	'comment_post_ID' => 1,
	'comment_author' => 'admin',
	'comment_author_email' => '[email protected]',
	'comment_author_url' => 'http://www.catswhocode.com',
	'comment_content' => 'Lorem ipsum dolor sit amet...',
	'comment_author_IP' => '127.0.0.1',
	'comment_agent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; fr; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3',
	'comment_date' => date('Y-m-d H:i:s'),
	'comment_date_gmt' => date('Y-m-d H:i:s'),
	'comment_approved' => 1,
);

$comment_id = wp_insert_comment($data);

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

WordPress hack: Insert comments programatically

WordPress hack: Get popular posts by comments count

Simply paste the following code where you want to display your most popular posts to be displayed:

$pop = $wpdb->get_results("SELECT id, post_title, comment_count FROM {$wpdb->prefix}posts WHERE post_type='post' ORDER BY comment_count DESC LIMIT 10");

<ul>
foreach($pop as $post) : ?>
<li> <?php echo $post->post_title; ?> </li>
<?php endforeach; ?>
</ul>

Thanks to Neil Skoglund for this nice piece of code!

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

WordPress hack: Get popular posts by comments count

10 sites developers should have in their bookmarks

Mysql Format Date

MySQL Format Date helps you to format your dates using the MySQL DATE_FORMAT function. Just select a common date format and then change it to your suit your needs. The MySQL DATE_FORMAT code will be generated at the bottom of the page which you can then copy into your query.
Visit site: http://www.mysqlformatdate.com

Script Src

Are you tired of hunting the Internet in order to find the script tag for the latest version of the Javascript library of your choice? ScriptSrc.net has compiled all the latest versions of jQuery, Mootools, Prototype and more in a single page which lets you copy it in your browser clipboard with a single click.

Visit site: http://scriptsrc.net

Em Chart

I never been a fan of ems in CSS files, but sometimes you have to deal with it. In that case, Em chart will translate ems to pixels so you’ll save time and hassle.

Visit site: http://aloestudios.com/tools/emchart

Twitter API Explorer

If you’re using the Twitter API in the site you build, you’ll for sure enjoy this very handy website which allow you to search through the Twitter API. Even better, the website can generate ready-to-use code snippets. A real time gain for you and your clients!

Visit site: http://twitapi.com/explore

Browser Sandbox

Cross browser compatibility is definitely one of the biggest problems a web developer has to face in his daily job. The browser sandbox lets you run any Windows browser from the web. The only bad thing is that you must run a Windows machine: The app does not work on Macs and GNU/Linux.

Visit site: http://spoon.net/browsers

PHP Forms

Web forms are one of the most important part of a website, but creating them is also very time-consuming. So, what about using a website that can speed up your form development for free?
PHP forms allows you to create advanced forms that can fit the needs of most websites.

Visit site: http://www.phpform.org

.htaccess editor

A .htaccess file is a must have for any website. Don’t know how to write one? No problem, just visit this site to create your .htaccess file using a wizard. It doesn’t allow very advanced stuff, but the results are great for 95% of the websites you’ll make.

Visit site: http://www.htaccesseditor.com/en.shtml

Smush it!

Images may be worth a thousand words, they’re also well known to use a lot of bandwidth. Images can be optimized for the web using programs like Photoshop; but if you don’t own a copy of this software or simply don’t have a clue how to do it, smush.it is what you need.
Brought to you by Yahoo developers network, Smush.it is an online tool that will reduce your image size without reducing their quality. For WordPress users, a very handy plugin for your favorite blogging engine is available here.

Visit site: http://developer.yahoo.com/yslow/smushit/

CSS Compressor

Especially on site with many different page layouts, CSS files can become huge and use a lot of server bandwidth. This tool, named CSS Compressor, can consequently reduce the size of any CSS file by removing comments, indentation and more.
Even better, compression level can be configured to fit your needs.

Visit site: http://www.csscompressor.com

Test everything

This site is a definitive must-have for your bookmarks: As the name says, Test everything allows you to test lot of things such as XHTML and CSS markup, PageRank, back-links, and a lot more.

Visit site: http://tester.jonasjohn.de

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

10 sites developers should have in their bookmarks

WordPress tip: Quickly secure plugin files

WordPress tip: Quickly secure plugin files

Paste the following in your .htaccess file. Don’t forget to backup the file before edition!

<Files ~ "\.(js|css)$">
  order allow,deny
  allow from all
</Files>

This recipe has been submitted by Greg Winiarski. Thanks for your contribution!

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

WordPress tip: Quickly secure plugin files

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