Support » Fixing WordPress » Anyone want to help me fix this little php issue with Facebook OG?

  • Hello. Im trying to make it so my Facebook OG tags will pull the og:image from my featured image per post. But having a hard time here..

    This is my current code

    function add_facebook_open_graph_tags() {
    	if (is_single()) {
    	global $post;
    	$image = get_post_meta($post->ID, 'og_custom_image', $single = true);
    	if (!$image)
    		$image = '';
    	<meta property="og:locale:alternate" content="ar_ar" /> <!-- optional -->
    	<meta property="og:locale" content="en_us" />
    	<meta property="og:title" content="<?php the_title(); ?>"/>
    	<meta property="og:type" content="article" />
    	<meta property="og:image" content="<?php echo $image; ?>" />
    	<meta property="og:url" content="<?php the_permalink(); ?>" />
    	<meta property="og:description" content="<?php echo $image = get_post_meta($post->ID, 'og_custom_des', $single = true); ?>" />
    	<meta property="og:site_name" content="<?php echo get_bloginfo('name'); ?>" />
    	<meta property="fb:app_id" content="215839858476754" />
    	<?php }
    add_action('wp_head', 'add_facebook_open_graph_tags', 99);

    This code is something i used on another site a while back, and im not sure i ever got it working right

    if single = Has Featured Thumbnail Then, Use as OG:image
    use default “image url”
    I tried putting
    <?php the_post_thumbnail(); ?>
    where og_custom_image currently is, which is a custom field, but no luck.

    so can anyone figure how to fix this?

Viewing 1 replies (of 1 total)
  • Michael


    Forum Moderator

    get_the_post_thumbnail() would return the full image tag, not just the image url;

    from the post ID, get the post thumbnail ID
    $post_thumb_id = get_post_thumbnail_id($post->ID);

    and with that get the attachment image src:
    $post_attachment_src = wp_get_attachment_image_src( $post_thumb_id, 'medium');

    where this is the image url:
    $image = $post_attachment_src[0];

    integrated into your code –
    – first priority: use featured image;
    – second priority: use custom field image;
    – otherwise use default image;

    (image selection part code only)

    $image = '';
             $post_thumb_id = get_post_thumbnail_id($post->ID);
             if( $post_thumb_id ) {
             $post_attachment_src = wp_get_attachment_image_src(  $post_thumb_id, 'medium'); //you might need to adjust the size
             $image = $post_attachment_src[0]; }
    	if (!$image) $image = get_post_meta($post->ID, 'og_custom_image', $single = true);
    	if (!$image)
    		$image = '';

    full code (untested)

Viewing 1 replies (of 1 total)
  • The topic ‘Anyone want to help me fix this little php issue with Facebook OG?’ is closed to new replies.