16-10-2010

PHP Wordpress add body_class using filter and conditionals

The Wordpress body_class function prints out classes to your body tag for use in CSS and JavaScript.

You can filter it to add your own custom body classes based on conditionals.

If you want to access the post inside the function you have to declare can refer to a global inside you function.

This is an example that adds a 'withheader' className to the body of the twentyten template based on whether an image is specified.

Add it to your theme's functions.php

function my_class_names($classes) {	
	global $wp_query ;
	$post = $wp_query->post;	
 
	if ( is_singular() && has_post_thumbnail( $post->ID ) &&
			( /* $src, $width, $height */ $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'post-thumbnail' ) ) && $image[1] >= HEADER_IMAGE_WIDTH ) {
		$classes[] = 'withheader';
	}	
 
	return $classes;
}

Comments:

Your comment:

»

 

[x]