How to get title of images in post content

Question

Today I have the function created below using regex that inserts the POST title if the ALT attribute of the image inserted in the content is empty.

But now I want to get the title of the image and not the post. How to make?

if( ! ( function_exists( 'add_alt_image_content' ) ) ) {
    function add_alt_image_content( $content ) {

        if ( is_single() && in_the_loop() && is_main_query() ) {

            global $post;

            $image = get_post( $post->ID );
            $image_title = $image->post_title;
    
            $pattern = '~(<img.*? alt=")("[^>]*>)~i';
            $replace = '$1'.$image_title.'$2';
            $content = preg_replace( $pattern, $replace, $content );
            
            return $content;
        }
    } 
}
add_filter( 'the_content', 'add_alt_image_content' );
0
Renan Bessa 2 months 0 Answers 13 views 0

Leave an answer