0

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

just change the $post->ID with get_post_thumbnail_id(), and possibly we can delete also the global $post;

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(get_post_thumbnail_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' );
5
  • 1
    but get_post_thumbnail is from the featured image. What I need is the name of the title of the other images inserted in the content. Nov 29 '20 at 2:19
  • I had been checking the code and the get_posts(1534) with an image id returns the proper code, and the $image_title gets the image name correctly, the code seems fine, I believe the problem is on the id that is introduced in get_posts() Nov 29 '20 at 2:33
  • 1
    But in this case I don't have the specific image ID information, as it will depend on the images inserted in the post's content. Nov 29 '20 at 3:05
  • it's possible to share the code where those images are being loaded, the post content?. Nov 29 '20 at 3:31
  • Maybe the with the function get_the_ID(); Nov 29 '20 at 3:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.