I want to add the featured image URL of a post to the header. When a Facebook user shares a WordPress page, this code in the header:
The rel="image_src"
attribute is what facebook is searching for.
<link rel="image_src" href="FEATUREDIMAGEURL">
Will return a specific image for the share. However, I cannot figure out how to add the URL of the post’s featured image… Can you?
I tried this:
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ); ?>
<link rel="image_src" href="<?php echo $image; ?>">
<?php endif; ?>
But it gave me a Parse error: syntax error, unexpected ';'
error.
To answer this one and point to the real problem:
As the
<head>
HTML tag comes far before the actual loop, you’ll need something else than theglobal $post
.The plugin
The code is tested and works.
As you might want to keep this functionality when switching themes, I’d suggest wrapping it up in a plugin.
So the actual plugin should be something around the following lines:
there was a closing bracket missing in the second line; and you need to reference the first array element of
$image
:http://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src
you might also want to add a check for single post or page, to avoid any unwanted output in index or archive pages; example: