请参阅以下代码。
我已经有一个代码将类别名称和标记名称提供给<body>
。但它只放入一个类别和一个标签,而不是全部。我需要在我的代码中更新一下,告诉wordpress它应该获取所有标签和类别并将其作为&#39; class&#39;进入<body>
?
// category-name to body
function add_category_name($classes = '') {
if( is_page() )
{
$category = get_the_category();
$classes[] = 'category-'.$category[0]->slug;
}
return $classes;
}
add_filter('body_class','add_category_name');
// tag-name in body
function add_tag_name($classes = '') {
if( is_page() )
{
$tag = get_the_tags( $post->ID );
$classes[] = 'tag-'.$tag[0]->slug;
}
return $classes;
}
add_filter('body_class','add_tag_name');
谢谢!
答案 0 :(得分:0)
<强>解强>
您可以将此代码添加到自定义functions.php文件中:
// add tags and categories to pages
function add_taxonomies_to_pages() {
register_taxonomy_for_object_type( 'post_tag', 'page' );
register_taxonomy_for_object_type( 'category', 'page' );
}
add_action( 'init', 'add_taxonomies_to_pages' );
if ( ! is_admin() ) {
add_action( 'pre_get_posts', 'category_and_tag_archives' );
}
function category_and_tag_archives( $wp_query ) {
$my_post_array = array('post','page');
if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) )
$wp_query->set( 'post_type', $my_post_array );
if ( $wp_query->get( 'tag' ) )
$wp_query->set( 'post_type', $my_post_array );
}
// add tags and categorys as class to <body>
function add_categories_and_tags( $classes = '' ) {
if( is_page() ) {
$categories = get_the_category();
foreach( $categories as $category ) {
$classes[] = 'category-'.$category->slug;
}
$tags = get_the_tags();
foreach( $tags as $tag ) {
$classes[] = 'tag-'.$tag->slug;
}
}
return $classes;
}
add_filter( 'body_class', 'add_categories_and_tags' );
完美,在WordPress 4.8中测试