2

hi i am try this code for display featured image after first paragraph and display image title and alt attribute

add_filter('the_content', function($content)
{
   $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
   $img = '<img src="'.$url.'" alt="" title=""/>';
   $content = preg_replace('#(<p>.*?</p>)#','$1'.$img, $content, 1);
   return $content;
});

featured image display correctly but title and alt attribute not show, please tell me anyone whats a problem in this code

3 Answers 3

1

Maybe following function is what you are looking for.
The important part you are looking for in the code is the line which holds the pathinfo,
which is php and not WordPress specific.

There are probably several other options but as nobody responded till now I think that this function will help you out till another (maybe better) answer is added by someone else.

You could make a backup of the functions.php (found in the theme folder) before you add this function to it.

I have tested it in a sandbox with the WP version 4.9.6 and it should work flawless.

/**
 * Add content on Alt/Title tags
 * 
 * @link    https://wordpress.stackexchange.com/q/306250
 * @version Wordpress V4.9.6 
 * 
 * Source:
 * @see     https://codex.wordpress.org/Function_Reference/wp_get_attachment_url
 * @see     https://secure.php.net/manual/en/function.pathinfo.php
 * @see     https://secure.php.net/manual/en/function.preg-replace.php
 * 
 * @param   [type] $content [description]
 * @return  [type]          [description]
 */
add_filter( 'the_content', 'add_filename_on_img_tags' );
function add_filename_on_img_tags( $content )
{
    // get featured image
    $url = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
    // get filename
    $filename = pathinfo( $arr['name'], PATHINFO_FILENAME );
    // add content on ALT/TITLE tags
    $img = '<img src="' . $url . '" alt="' . $filename . '" title="' . $filename . '"/>';
    // add image after first paragraph
    $content = preg_replace( '#(<p>.*?</p>)#','$1' . $img, $content, 1 );

    return $content;

} // end function

In the docblock you find links with information for code as used in the function.

0

You have nothing in the code to display those values, try:

$img = '<img src="'.$url.'" alt="'.get_the_title().'" title="'.get_the_title().'"/>';
1
  • This is working perfectly but this code retrieve post title in image title and alt attribute, but i want to show image name in title and alt attribute Jun 16, 2018 at 17:23
-1

You can use this as well.

the_post_thumbnail( 'large', array( 'title' => get_the_title(get_post_thumbnail_id()),'alt' => get_the_post_thumbnail_caption() ) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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