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
Add a comment  | 

2 Answers 2

Reset to default 0

I 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)