Skip to content

Instantly share code, notes, and snippets.

@dboutote
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dboutote/a2c7086b6f1d30706521 to your computer and use it in GitHub Desktop.
Save dboutote/a2c7086b6f1d30706521 to your computer and use it in GitHub Desktop.
Add an ID Attribute to WordPress Body Element
<?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( 'body_id', $id );
};
// Print id on body elements
function body_id( $id = '' ) {
if ( '' == $id ) {
$id = get_body_id();
}
$id = preg_replace("#\s+#", " ", $id);
$id = str_replace(' ', '-', strtolower($id) );
echo ( '' != $id ) ? 'id="'.$id. '"': '' ;
};
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment