admin管理员组文章数量:1122846
I'd like to add a category class to body_class for custom post type to change body background color. I tried to rework the following code to work with custom post types, but no dice. It works with posts, but not the custom post type.
add_filter('body_class','add_category_to_single');
function add_category_to_single($classes) {
if (is_singular() ) {
global $post;
foreach((get_the_category($post->ID)) as $category) {
// add category slug to the $classes array
$classes[] = $category->category_nicename;
}
}
// return the $classes array
return $classes;
}
I'm using Pods plugin and the latest WP.
I'd like to add a category class to body_class for custom post type to change body background color. I tried to rework the following code to work with custom post types, but no dice. It works with posts, but not the custom post type.
add_filter('body_class','add_category_to_single');
function add_category_to_single($classes) {
if (is_singular() ) {
global $post;
foreach((get_the_category($post->ID)) as $category) {
// add category slug to the $classes array
$classes[] = $category->category_nicename;
}
}
// return the $classes array
return $classes;
}
I'm using Pods plugin and the latest WP.
Share Improve this question asked Aug 11, 2024 at 13:20 Single_peteSingle_pete 111 bronze badge2 Answers
Reset to default 2your code only works if you are using category
taxonomy.
if you are using custom taxonomy like brands
you must change your code to this:
function add_category_to_single( $classes ) {
if ( is_singular() ) {
global $post;
$taxonomy = 'brands';
$terms = get_the_terms( $post->ID, $taxonomy );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
$classes[] = $term->slug;
}
}
}
return $classes;
}
add_filter( 'body_class', 'add_category_to_single' );
Wordpress as designed will add the class of the post type that you create to the body class list.
As an example if your post type is wspe_cats
, wordpress will inject single-wspe-cats
to the body of the single post for your CPT.
Similarly it will do the same for that CPT archive.
Let's say I create a taxonomy for my cpt called wspe-breeds
, and set 3 terms (black
, white
, calico
).
If I have an archive post for wspe_cats
, WordPress will automatically add archive tax-wspe-breeds
to the body.
If I went to the archive for my custom post taxonomy to look at calico cats, WordPress will automatically add archive tax-wspe-breeds
to the body along with the these additional classes term-calico term-3
to the body of that archive. (Three came from the fact that that is the term's ID.)
So, if I'm reading your question correctly, there is no code that you need to create...WordPress did the heavy lifting!
本文标签: Add body class to custom post type
版权声明:本文标题:Add body class to custom post type 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736297985a1930130.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论