/ Published in: PHP
                    
                                        
Add a custom ID to the body, useful for when the classes added to the body aren't descriptive enough on pages like Archives and single
                
                            
                                Expand |
                                Embed | Plain Text
                            
                        
                        Copy this code and paste it in your HTML
<?php
// Create a dynamic id on body elements
function get_body_id( $id = '' ) {
global $wp_query;
// Fallbacks
if ( is_front_page() ) $id = 'front-page';
if ( is_home() ) $id = 'blog';
if ( is_search() ) $id = 'search';
if ( is_404() ) $id = 'error404';
// If it's an Archive Page
if ( is_archive() ) {
if ( is_author() ) {
$author = $wp_query->get_queried_object();
$id = 'archive-author-' . sanitize_html_class( $author->user_nicename , $author->ID );
} elseif ( is_category() ) {
$cat = $wp_query->get_queried_object();
$id = 'archive-category-' . sanitize_html_class( $cat->slug, $cat->cat_ID );
} elseif ( is_date() ) {
if ( is_day() ) {
$date = get_the_time('F jS Y');
} elseif ( is_month() ) {
$date = get_the_time('F Y');
} elseif ( is_year() ) {
$date = get_the_time('Y');
} else {
$id = 'archive-date';
}
} elseif ( is_tag() ) {
$tags = $wp_query->get_queried_object();
$id = 'archive-tag-' . sanitize_html_class( $tags->slug, $tags->term_id );
} else {
$id = 'archive';
}
}
// If it's a Single Post
if ( is_single() ) {
if ( is_attachment() ) {
$id = 'attachment-'.$wp_query->queried_object->post_name;
} else {
$id = 'single-'.$wp_query->queried_object->post_name;
}
}
// If it's a Page
if ( is_page() ) {
$id = 'page-'.$wp_query->queried_object->post_name;
if ('' == $id ) {
$id = 'page';
}
}
// If $id still doesn't have a value, attempt to assign it the Page's name
if ('' == $id ) {
$id = $wp_query->queried_object->post_name;
}
// Let other plugins modify the function
return apply_filters( 'body_id', $id );
};
// Print id on body elements
function body_id( $id = '' ) {
if ( '' == $id ) {
$id = get_body_id();
}
echo ( '' != $id ) ? 'id="'.$id. '"': '' ;
};
?>
URL: http://darrinb.com/notes/2010/adding-a-custom-id-to-the-body-element-in-wordpress/
Comments
 Subscribe to comments
                    Subscribe to comments
                
                