How can I attach Facebook Open Graph data to an Attachment Page?

I have code in my page header which properly creates the Open Graph tags for pages, posts, etc. However, when I attempt to Share an attachment post from the Media Library (not the actual attachment image, but rather the URI) no Open Graph tags get shared. Is this possible to do? If so, how?

Eg. the WordPress URL is

http://example.com/part-150-study/

Which properly redirects (301) to

http://example.com/wp-content/uploads/part-150-study.pdf

When I use the Facebook OG Object Debugger, it shows a response code of 206

 The following will be treated as a redirect by the crawler:

    A HTTP redirect
    A link rel="canonical" href=".." / tag
    A meta property="og:url" content=".." / tag

 The final URL, which we tried to extract metadata from is highlighted in bold.

It also shows that the final page (the PDF) is a 301 redirect.

Here is the code I put in my header. Which (again) works FINE for all post types. But not attachments.

function insert_fb_in_head() {

    $og_title = get_post_meta( get_the_ID(), '_yoast_wpseo_title', true);
    if( ! $og_title)    
        $og_title = get_the_title();

    echo ('meta property="og:title" content="' . $og_title . '"/' . PHP_EOL);
    echo ('meta property="og:type" content="article"/' . PHP_EOL);
    echo ('meta property="og:url" content="' . get_permalink() . '"/' . PHP_EOL);
    echo ('meta property="og:site_name" content="Noise Information"/' . PHP_EOL);
    echo ('meta property="og:description" content="' . strip_tags( get_post_meta( get_the_ID(), '_yoast_wpseo_metadesc', true), '' ) . '"/' . PHP_EOL);

    if( has_post_thumbnail( $post-ID )) { //the post has a featured image, use a default image
    $thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post-ID ), 'full' );
    echo ('meta property="og:image" content="' . esc_attr( $thumbnail_src[0] ) . '"/' . PHP_EOL);
    echo ('meta property="og:image:width" content="' . esc_attr( $thumbnail_src[1] ) . '"/' . PHP_EOL);
    echo ('meta property="og:image:height" content="' . esc_attr( $thumbnail_src[2] ) . '"/' . PHP_EOL);      
}

    $default_image="http://example.com/wp-content/uploads/airplane-250.png"; 
    echo ('meta property="og:image" content="' . $default_image . '"/' . PHP_EOL);
    echo ('meta property="og:image:width" content="250"/' . PHP_EOL);
    echo ('meta property="og:image:height" content="250"/' . PHP_EOL);        
 }
 add_action( 'wp_head', 'insert_fb_in_head', 5 );

I've Googled until I'm blue in the face and found nothing.

Topic open-graph facebook attachments Wordpress

Category Web

About

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