How to get full absolute url for post attachment?

I'm trying to manually fill the Open Graph tags and I'm having some troubles in setting the content for the og:image tag.

In a single post page, I set it this way:

?php
$thumbnailSrc = wp_get_attachment_image_src(get_post_thumbnail_id($post-ID), 'medium');
$image        = esc_attr($thumbnailSrc[0]);
?
meta property="og:image" content="?php echo $image ?"

The result is this:

meta property="og:image" content="/wp-content/uploads/image.jpg"

On the Open Graph debugger I then get this error:

Object at URL 'http://website.com' of type 'article' is invalid because the given value '/wp-content/uploads/image.jpg' for property 'og:image:url' could not be parsed as type 'url'.

How can I get the attachment so that the url is: http://website.com/wp-content/uploads/image.jpg ?

Topic open-graph post-thumbnails images Wordpress

Category Web


To access the current post object outside The Loop, you need to declare the $post variable globally.

<?php global $post; ?>
<meta property="og:image" 
    content="<?php echo wp_get_attachment_url(get_post_thumbnail_id(($post->ID)); ?>">

You could use has_post_thumbnail() and get_the_post_thumbnail_url() to get an absolute url for the posts feature image.

According to the Codex has_post_thumbnail() will check if the post has an image attached and get_the_post_thumbnail_url() will return the post thumbnail URL.

I have tested the code below:

global $post;
if ( has_post_thumbnail($post->ID) ) {
  echo '<meta property="og:image" content="'.get_the_post_thumbnail_url($post->ID).'">';
}

As mentioned in a previous comment, you are using the $post object before the WordPress loop starts and will need to declare global $post; before you can use $post->ID.


esc_attr() might not be necessary on the url retrieved by wp_get_attachment_image_src.

I have referred to a code example from the WordPress Codex page on wp_get_attachment_image_src and adapted the following code that works for me.

global $post;
$thumbnailSrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');
if ( $thumbnailSrc ) :
  echo '<meta property="og:image" content="'.$thumbnailSrc[0].'">';
endif;

Edit: Since you are using the $post object outside of the WordPress loop you will need to declare global $post; before you use $post->ID. I have added it to the code sample above.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.