gpt4 book ai didi

html - Wordpress:将多个类别名称和标签名称从页面添加到

转载 作者:行者123 更新时间:2023-11-28 03:24:28 24 4
gpt4 key购买 nike

请引用下面的代码。

我已经有一个代码可以为 <body> 提供类别名称标签名称 .但它只放入一个类别和一个标签,而不是全部。我必须在我的代码中更新什么以告诉 wordpress 它应该获取所有 标签类别 并将其作为“类”放入 <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 中测试

关于html - Wordpress:将多个类别名称和标签名称从页面添加到 <body>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45058866/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com