• I need to add an ID to a displayed post title which currently doesn’t have one within a wordpress site using a child theme.

    I have been using the code below in the child theme’s functions file, which works well in adding an ID to any h1 to h6 which doesn’t have one (& leaves any that do alone) but this works only WITHIN the post content (the_content) and it wont add an ID to the displayed post title (see h1 class=”entry-title… on the page [ redundant link removed ]).

    Can anyone tell me how I can add an ID to the displayed post title, using a filter like the one below?

    Many thanks

    /**
     * Automatically add IDs to headings such as <h2></h2>
     */
    function auto_id_headings( $content ) {
    
    	$content = preg_replace_callback( '/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i', function( $matches ) {
    		if ( ! stripos( $matches[0], 'id=' ) ) :
    			$matches[0] = $matches[1] . $matches[2] . ' id="' . sanitize_title( $matches[3] ) . '">' . $matches[3] . $matches[4];
    		endif;
    		return $matches[0];
    	}, $content );
    
        return $content;
    
    }
    add_filter( 'the_content', 'auto_id_headings' );
    • This topic was modified 4 years, 6 months ago by Jan Dembowski.

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Assuming your theme calls the_title(), use “the_title” filter to alter the output HTML in a manner similar to “the_content” filter.

Viewing 1 replies (of 1 total)
  • The topic ‘Automatically add ID to displayed post title’ is closed to new replies.