Use WordPress Custom Post Type In CSS-Class for Styling
Today I would like to show you, how to assign CSS classes to custom post types for styling your website.
Basically we just extend the function body_class()
of WordPress with our own post types, so that we can address them to style our design accordingly.
The same I had already explained in detail in another post where the title of a post has been incorporated into this function, so there you can find additional information.
// Adds classes for custom post types to body_class() and post_class() function fb_add_body_class( $class ) { $post_type = 'my_example_post_type'; // the Post Type if ( get_query_var('post_type') === $post_type ) { // only, if post type is active $class[] = $post_type; $class[] = 'type-' . $post_type; } return $class; } add_filter( 'body_class', 'fb_add_body_class' );
Alternatively you can extend the function post_class()
so you won’t have the class of the custom post type directly at the body tag. Therefore I use the same function and we just address the hook of the post class.
add_filter( 'post_class', 'fb_add_body_class' );
Both template tags are used in HTML tag, as it shown on the codex pages, we have mentioned above; and here is an example for the post class:
<div <?php post_class('class-name'); ?>>
Enjoy testing and using it, if you know any improvements or have any question, please feel free and leave a comment.
Update: A small example for the custom taxonomie inside this fucntions of WordPress
function fb_add_body_class( $class ) { if ( ! is_tax() ) return $class; $tax = get_query_var( 'taxonomy' ); $term = $tax . '-' . get_query_var( 'term' ); $class = array_merge( $classes, array( 'taxonomy-archive', $tax, $term ) ); return $class; } add_filter( 'body_class', 'fb_add_body_class' ); // or post_class as hook
Use or fork it and have an idea or small solution for your requirements.
Just to note, WordPress will automatically adds in some classes to the body tag for your custom post types. By default it will add:
“single-myposttype” on individual custom post type pages
and:
“post-type-archive-myposttype” for custom post type archives.
Seconded to Ben’s comment. This is still a great article that is applicable to taxonomies as well as any other custom query vars that may be registered with WordPress.
@Hunter: yes, its also possible; see my gist as example