Add a Custom ID to the Body Element in WordPress


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. <?php
  2. // Create a dynamic id on body elements
  3. function get_body_id( $id = '' ) {
  4. global $wp_query;
  5.  
  6. // Fallbacks
  7. if ( is_front_page() ) $id = 'front-page';
  8. if ( is_home() ) $id = 'blog';
  9. if ( is_search() ) $id = 'search';
  10. if ( is_404() ) $id = 'error404';
  11.  
  12. // If it's an Archive Page
  13. if ( is_archive() ) {
  14. if ( is_author() ) {
  15. $author = $wp_query->get_queried_object();
  16. $id = 'archive-author-' . sanitize_html_class( $author->user_nicename , $author->ID );
  17. } elseif ( is_category() ) {
  18. $cat = $wp_query->get_queried_object();
  19. $id = 'archive-category-' . sanitize_html_class( $cat->slug, $cat->cat_ID );
  20. } elseif ( is_date() ) {
  21. if ( is_day() ) {
  22. $date = get_the_time('F jS Y');
  23. $id = 'archive-day-' . str_replace(' ', '-', strtolower($date) );
  24. } elseif ( is_month() ) {
  25. $date = get_the_time('F Y');
  26. $id = 'date-' . str_replace(' ', '-', strtolower($date) );
  27. } elseif ( is_year() ) {
  28. $date = get_the_time('Y');
  29. $id = 'date-' . strtolower($date);
  30. } else {
  31. $id = 'archive-date';
  32. }
  33. } elseif ( is_tag() ) {
  34. $tags = $wp_query->get_queried_object();
  35. $id = 'archive-tag-' . sanitize_html_class( $tags->slug, $tags->term_id );
  36. } else {
  37. $id = 'archive';
  38. }
  39. }
  40.  
  41. // If it's a Single Post
  42. if ( is_single() ) {
  43. if ( is_attachment() ) {
  44. $id = 'attachment-'.$wp_query->queried_object->post_name;
  45. } else {
  46. $id = 'single-'.$wp_query->queried_object->post_name;
  47. }
  48. }
  49.  
  50. // If it's a Page
  51. if ( is_page() ) {
  52. $id = 'page-'.$wp_query->queried_object->post_name;
  53. if ('' == $id ) {
  54. $id = 'page';
  55. }
  56. }
  57.  
  58. // If $id still doesn't have a value, attempt to assign it the Page's name
  59. if ('' == $id ) {
  60. $id = $wp_query->queried_object->post_name;
  61. }
  62.  
  63. $id = preg_replace("#\s+#", " ", $id);
  64. $id = str_replace(' ', '-', strtolower($id) );
  65.  
  66. // Let other plugins modify the function
  67. return apply_filters( 'body_id', $id );
  68.  
  69. };
  70.  
  71. // Print id on body elements
  72. function body_id( $id = '' ) {
  73. if ( '' == $id ) {
  74. $id = get_body_id();
  75. }
  76.  
  77. $id = preg_replace("#\s+#", " ", $id);
  78. $id = str_replace(' ', '-', strtolower($id) );
  79.  
  80. echo ( '' != $id ) ? 'id="'.$id. '"': '' ;
  81. };
  82. ?>

URL: http://darrinb.com/notes/2010/adding-a-custom-id-to-the-body-element-in-wordpress/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.