filters - Add id attribute to h1 element of wordpress post

admin2025-01-07  5

The default rendering of the h1 element of a wordpress post looks like this:

<h1 class="entry-title"> XYZ </h1>

I would like to add the id attribute to the h1 element with the value of the post's title. The result should look as follows

<h1 id="XYZ" class="entry-title"> XYZ </h1>

I have already looked through many posts here, but couldn't find an answer to my question. Shouldn't there be a simple filter for functions.php to override the rendering of the h1 element?

The default rendering of the h1 element of a wordpress post looks like this:

<h1 class="entry-title"> XYZ </h1>

I would like to add the id attribute to the h1 element with the value of the post's title. The result should look as follows

<h1 id="XYZ" class="entry-title"> XYZ </h1>

I have already looked through many posts here, but couldn't find an answer to my question. Shouldn't there be a simple filter for functions.php to override the rendering of the h1 element?

Share Improve this question asked Sep 2, 2018 at 14:46 betabeta 2031 gold badge2 silver badges9 bronze badges 2
  • 2 WordPress doesn’t render the h1 element. So there’s no hook. Your theme does. The h1 will be in your theme’s templates somewhere. – Jacob Peattie Commented Sep 2, 2018 at 14:47
  • just found it. looked in the wrong place the whole time. should I delete the question? – beta Commented Sep 2, 2018 at 14:54
Add a comment  | 

2 Answers 2

Reset to default 0

You have to use the code editor. Be careful, do not write the head part, HTML tag and body tag. The syntax would be:

<h1 id="XYZ">XYZ</h1>

you can achieve this by adding a filter to modify the output of the post title in wordpress

When the filter is working mode then it checks if the current page is a single post is_singular('post'). If it is, it retrieves the post title, sanitizes it, and adds it as the id attribute to the <h1> element along with the existing title class. Then it returns the modified title

Add the following code to your themes functions.php file

function add_id_to_post_title_h1( $title, $id = null ) {
    if ( is_singular('post') ) { // Check if it's a single post
        $post = get_post($id);
        $title = '<h1 id="' . esc_attr( sanitize_title( $post->post_title ) ) . '" class="entry-title">' . $title . '</h1>';
    }
    return $title;
}
add_filter( 'the_title', 'add_id_to_post_title_h1', 10, 2 );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736253179a104.html

最新回复(0)