Search code examples
wordpressfacebook-opengraph

Dynamically inserting og:image on a WordPress page


I'm using the following function, and am using FB's debugger on a page that I'm certain has a featured image set:

function fb_opengraph() {
    global $post;

    if(is_page()) {

        if(has_post_thumbnail($post->ID)) {
            $img_src = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium');
        } else {
            $img_src = get_stylesheet_directory_uri() . '/img/opengraph_image.jpg';
        }
        if($excerpt = $post->post_excerpt) {
            $excerpt = strip_tags($post->post_excerpt);
            $excerpt = str_replace("", "'", $excerpt);
        } else {
            $excerpt = get_bloginfo('description');
        }
        ?>

    <meta property="og:title" content="<?php echo the_title(); ?>"/>
    <meta property="og:description" content="<?php the_content(); ?>"/>
    <meta property="og:type" content="article"/>
    <meta property="og:url" content="<?php echo the_permalink(); ?>"/>
    <meta property="og:site_name" content="<?php echo get_bloginfo(); ?>"/>
    <meta property="og:image" content="<?php echo $img_src; ?>"/>

<?php
    } else {
        return;
    }
}
add_action('wp_head', 'fb_opengraph', 5);

What's currently happening is that $img_src is coming back with the value "Array", and not with the URL for the featured image for that page. I'm not sure where this "Array" value is even coming from, but more importantly am trying to pull in the featured image URL with no luck.

Any ideas? Thanks!


Solution

  • https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/

    This should give you an array

    wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium');
    

    for getting the url you need to get appropriate array element

    $img_src = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium')['url'];
    

    Give it a try