Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add an ID Attribute to the WordPress Body Element: http://darrinb.com/adding-a-custom-id-to-the-body-element-in-wordpress/
<?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');
$id = 'archive-day-' . str_replace(' ', '-', strtolower($date) );
} elseif ( is_month() ) {
$date = get_the_time('F Y');
$id = 'date-' . str_replace(' ', '-', strtolower($date) );
} elseif ( is_year() ) {
$date = get_the_time('Y');
$id = 'date-' . strtolower($date);
} 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;
}
$id = preg_replace('/\s+/', ' ', $id);
$id = str_replace(' ', '-', strtolower($id) );
// Let other plugins modify the function
return apply_filters( 'get_body_id', $id );
};
/**
* Print a dynamic id on body elements
*
*/
function body_id( $id = '' ) {
if ( '' == $id ) {
$id = get_body_id();
}
$id = preg_replace('/\s+/', ' ', $id);
$id = str_replace(' ', '-', strtolower($id) );
$id = apply_filters( 'body_id', $id );
echo ( '' != $id ) ? 'id="'.$id. '"' : '' ;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.