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?
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 );