jave.web
jave.web

Reputation: 15032

Dynamicly create facebook thumbnails in WordPress theme

The facebook suggests to put an :og metatag inside your page, but I need to create it dynamicly for each WordPress post/single - but in header I am not in the loop yet - how do I get the page/single thumbnail, while not in loop yet ? :)

I ended up with:

<?php global $post; $id = $post->ID; ?>
<meta name="og:image" content="<?php 
   $thumbieLink = wp_get_attachment_url( get_post_thumbnail_id($id) ); 
   if( $thumbieLink!==false && $thumbieLink!="" ) echo $thumbieLink;
      else echo "http://IfNoThumbNailIsAvailable.com/default.jpg"; 
?>" />

Reason why I use a bit different meta tag than the standard is because I dont want to add XHTML doctype to my site - see http://code.adonline.id.au/valid-meta-tags-for-facebook-link-thumbnails/ for more info :) XML is great, XHTML is evil.

Upvotes: 0

Views: 79

Answers (1)

Marcel Macasso
Marcel Macasso

Reputation: 56

global $post;
$id = $post->ID;

You can use this anywhere outside of the loop to get the post/page id. Now you can use the standard Wordpress functions to get the featured image, post excerpt etc.

$imageUrl = wp_get_attachment_url( get_post_thumbnail_id($id) );

With this line you get the featured image url. Now you can echo the og:image tag that facebook requires.

Upvotes: 3

Related Questions