向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
<?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(); } 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. '"': '' ; }; ?>
以上是关于向WordPress中的Body元素添加自定义ID的主要内容,如果未能解决你的问题,请参考以下文章