Wordpress:将多个类别名称和标签名称从页面添加到 <body>

Wordpress: Adding multiple category-names & tag-names from page to <body>

请参考以下代码。

我已经有一个代码可以将 category-namestag-names 提供给 <body>。但它只放入一个 category 和一个 tag,而不是全部。我必须在我的代码中更新什么来告诉 wordpress 它应该获取所有 tagscategories 并将其作为 'class' 放入<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');

谢谢!

解决方案

您可以将此代码添加到您的自定义 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 中测试