Get Social

WordPress: How To Show The Featured Image Of Posts In Social Sharing Sites

We all see people sharing links with images attached to them, on Facebook and Friendfeed. Most other sharing sites also support adding an image to your shares automatically.

This is simply done by a meta link tag: <link rel="image_src" href="your_image_url" />

If your WordPress template supports featured images, it is relatively easy to add this meta tag. Open your template’s php file, which sends out the headers (meta tags, link tags, title, etc, everything between the <head> </head> tags). The file you’ll be changing most probably is named header.php. Some themes have headers in index.php. So check these two files out.

Add these three lines of codes inside the head tags:

<?php if ( is_single() and function_exists('has_post_thumbnail') and has_post_thumbnail($post->ID) ) : ?>
<link rel="image_src" href="<?php $thumb = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium'); echo $thumb[0]; ?>" />
<?php endif; ?>

If your image has a post thumbnail (featured image) attached to it, this code will create the link tag. Now when anybody shares this post on social sites, your post thumbnail will appear. You can change the size of the image to thumbnail, medium, large or full. But sharing sites most probably will resize it.

If your theme comes with other thumbnail sizes, you can find them in functions.php file of your theme. Look for a line starting with add_image_size() wp function, and you can find the name of the attachment.

But my theme does not support featured images?

Then you have two solutions for the problem. First, you can force your theme to support post thumbnails. You’ll be able to add an image to your posts, but you’ll not be able to see it when you publish the post. However, the attachment will be made, and link tag will be created for you.

To enable the thumbnail support, open your theme’s functions.php file, and add these lines at the beginning.

add_theme_support('post-thumbnails', array( 'post' ));
add_image_size('link-thumbnail', 200, 200, true)

Now you have thumbnail support. Plus, the second line adds a new kind of image size called “link-thumbnail” with size of 200px width and height, which you can use in the link tag creation. You can change the “true” part at the end, if you do not want to smart-crop your images.

Remember, you’ll also need to insert the first code I gave into your header.php (or again to index.php depending on your theme) file.

Don’t need thumbnail support, what is the second solution?

Well, you can check for images in the post content, and use the first image as a link tag. Again in the head section of your theme (either in your theme’s header.php or index.php as I mentioned earlier) you’ll need to add these lines of code:

<?php
if ( is_single() ) :
	$postimages = array();
 	preg_match_all('@<img.+src="(.*)".*>@Uims' , $post->post_content, $postimages);
	$image = end($postimages);
?>
<?php if($image): ?>
<link rel="image_src" href="<?php echo $image[0]; ?>" />
<?php endif;
endif;
?>

This will get the post’s attachments, and create the link tag from the first one.

An addition for those who have the post thumbnails support

You can also add the last code I gave here. Even if you did not attach any post thumbnails but included some images in your posts, your post will be shared with an image.

And the end…

It is possible to have more than one link image tag in your posts. You can alter the last code to include all your images (you might have seen how on Facebook some links come with more than one thumbnails while you are adding a link). To accomplish this, the last code I gave you becomes:

<?php
if ( is_single() ):
	$postimages = array();
 	preg_match_all('@<img.+src="(.*)".*>@Uims', $post->post_content, $postimages);
?>
<?php foreach($postimages[1] as $image): ?>
<link rel="image_src" href="<?php echo $image; ?>" />
<?php endforeach;
endif;
?>

After you arranged your files with the new code, try sharing one of your posts on Facebook, Friendfeed or some other site that supports images with links. If it is not working for you, you might be doing something wrong, leave a comment.

Have fun :)

11 CommentsLeave a Comment


  • Reply

    M

    6 months ago

    Selam, buradakileri yapınca Blogger blogroll’da da thumbnail görünür mü acaba?

    • Reply

      emrahgunduz

      6 months ago

      Blogroll tam olarak nasıl çalışıyor bilmiyorum. Eğer blogun direkt kendisine bakarak link-rel taglerini kontrol ediyorsa çalışacaktır.

      Fakat RSS ile alıyorsa, ne yazık ki çalışmaz. RSS’e resim eklemek için http://emrg.me/6h bu yazıya bakabilirsiniz.

      (Blogger WordPress’den farklı bir ortam olduğu için bu kodları kullanmak mümkün olmayacaktır.)

      • Reply

        M

        6 months ago

        Sitenizi tekrar bulmak için çok uğraştım, kusura bakmayın geç cevap yazabildim. Sanırım RSS’ye resim eklemek soruma çözüm olacak zira Blogspot’ta blogroll kısmında WordPress üzerinden yazılan hiçbir blogun thumbnail resimleri çıkmıyor. Thumbnail eklentisi kullansak bile. Çok teşekkürler.

  • Reply

    Arek

    6 months ago

    Thanks for the tips! . I was wondering if there is there any way to display all featured images from all posts in one place. I want to create gallery from featured images to make them act like links to the posts.

    • Reply

      emrahgunduz

      6 months ago

      What you want is actually what I’m doing at the bottom of my blog, in other links section. I’m displaying the featured images of portfolio posts in thumbnail size. Here is the code I’m using.

      < ?php
      $portfoliolist = get_posts(array(
      	'numberposts' => -1,
      	'orderby' => 'date',
      	'post_type'	=> array('posts'), // You may want to remove or change this line
      	'order'		=> 'DESC'
      ));
      ?>
      
      
        < ?php if ($portfoliolist) : ?> < ?php foreach($portfoliolist as $post) : ?> < ?php setup_postdata($post); ?> < ?php if(has_post_thumbnail()) : ?>
      • < ?php the_post_thumbnail("post-thumbnail", array( 'alt'=>get_the_title_rss(), 'title'=>get_the_title_rss()) ); // You can use the_permalink() for getting the url of the post ?>
      • < ?php endif; ?> < ?php endforeach; ?> < ?php endif; ?>

      I think it’s not hard to understand what is going in here. Get a bunch of posts, list them as images inside links inside a loop. Hope this helps.

  • Reply

    Roxana

    6 months ago

    Emrah, my wordpress theme supports featured image. I copied & pasted your code, and yet I still can’t get it to work. ='(
    Will you help me out, pleeassee.

    • Reply

      emrahgunduz

      6 months ago

      Are you attaching featured images to your posts? If you can add your blog url, I may help you.

      • Reply

        Roxana

        6 months ago

        Hey Emrah, thanks for responding so quickly! Yes, the featured images are attached to the posts. I’ve included the website here. Thank you so much for your time. I appreciate this. You rock! ;)

      • Reply

        Roxana

        6 months ago

        Hey Emrah, is this not possible for my wp blog?

        • Reply

          emrahgunduz

          6 months ago

          When I checked your blog, I can only see

           
           
           

          Are you sure you have inserted the code I wrote in the post correctly?
          It seems like you just inserted only a link rel into your theme by hand, and the href part is wrong. It is not your domain.

  • Reply

    fatih

    2 months ago

    Merhaba, ing olduğundan pek anlamadım ama yaptığım arama sonuçlarına göre şu kod ile oluyormuş. Bu şekilde yaptım ama kaynaktaki görüntüsü pek hoşuma gitmedi. Yan yana durdu diğerleri ile :( Temaya entegre edemedim malesef sizin kodu.

    function add_image_src(){

    global $post;
    // get the global variable post
    // if it exists and is only a single post
    if ($post){

    // pattern for recognizing first image in post
    $pattern = ‘!post_content, $matches);

    //first image would be the representative image
    $image_src = $matches['1'][0];
    // extract it as Facebook wants it
    echo ”;
    }
    }

    // hooking to the head generation loop my function defined above
    add_action(‘wp_head’, ‘add_image_src’);

Leave a Reply