向WordPress中的Body元素添加自定义ID

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了向WordPress中的Body元素添加自定义ID相关的知识,希望对你有一定的参考价值。

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
  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. ?>

以上是关于向WordPress中的Body元素添加自定义ID的主要内容,如果未能解决你的问题,请参考以下文章

PHP 使用PHP向body元素添加唯一ID

使用PHP向body元素添加唯一的ID

从 DOM 中读取 HTML 片段并向其中添加自定义数据

将自定义类添加到 WordPress 导航中的锚标记

向WordPress添加自定义图像大小

如何向 WordPress Gutenberg 块添加自定义块?