admin管理员组文章数量:1122846
How to add Category name to post title (H1)? “PostTitle + CategoryName”?
My h1 post title code:
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
How to add Category name to post title (H1)? “PostTitle + CategoryName”?
My h1 post title code:
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
Share
Improve this question
asked Jun 7, 2018 at 20:43
SeryozhaSeryozha
191 silver badge2 bronze badges
1
- 1 Remember a post can be in multiple categories. – bravokeyl Commented Jun 8, 2018 at 3:21
2 Answers
Reset to default 0I would work the code arround and do something like this.
<h1><?php echo get_the_title(); ?> - <?php the_category(', '); ?></h1>
get_the_title();
Retrieve post title.
the_category(', ');
Displays links to categories, each category separated by a comma (if more than one).
Documentation can be founded here : https://codex.wordpress.org/Function_Reference/the_category
Hope it helps you.
There are two solutions you can use.
Change it in the theme
If you can just modify the line that is printing the title, then do it. You can replace it with:
<h1><?php the_title(); ?> - <?php the_category(); ?></h1>
And if the categories shouldn't be linked, then you can use this:
<h1><?php the_title(); ?> - <?php
$categories = get_the_category();
if ( ! empty($categories) ) {
foreach ( $categories as $term ) {
echo esc_html( $term->name ) . ' ';
}
}
?></h1>
If you can't change the theme
Or you don't want to, because there are many, many places you'd have to change, then you can use the_title
filter:
function add_categories_to_the_title( $title, $id ) {
if ( is_singular( 'post' ) && 'post' == get_post_type( $id ) ) { // it will work only for posts on single page, but you can modify this condition
$categories = get_the_category();
$cats_string = '';
if ( ! empty($categories) ) {
foreach ( $categories as $term ) {
$cats_string .= $term->name . ' ';
}
}
if ( $cats_string ) {
$title .= ' - ' . $cats_string;
}
}
return $title;
}
add_filter( 'the_title', 'add_categories_to_the_title', 10, 2 );
本文标签: categoriesAdd Category name to Post Title (h1)
版权声明:本文标题:categories - Add Category name to Post Title (h1) 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736293569a1929173.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论