Dynamic Twitter card images

I'm creating some images from WP posts using HTML5 Canvas and saving them to my uploads folder. I'm then sharing them to Facebook, which works fine, but to share to Twitter I need to update the Twitter Meta tags with the image URL's. I'm aware I can't do this with JS and need to do it server side, but I can't work out how to to this...

I'm using the following function in functions,php

add_action('wp_ajax_nopriv_canvasUpload', 'canvasUpload');
add_action('wp_ajax_canvasUpload', 'canvasUpload');

function canvasUpload(){
$uploads = wp_upload_dir();
$img = $_POST['uploadImage'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);


global $file;
$uploads = wp_upload_dir(); 
$file = $uploads['path'].'/'. uniqid() . '.png';
echo $file;

return 
$r = file_put_contents($file, $data);
echo $r ? $file : 'Error saving file';
}




function add_twitter_cards() {
    if(is_single()) {
    $tc_url    = get_permalink();
    $tc_title  = get_the_title();
    //$tc_description   = get_the_excerpt();

    global $post;
    global $file;

    $tc_image = wp_get_attachment_image_src( get_post_thumbnail_id($post-ID), 'full' );
    $tc_image_thumb  = $tc_image[0];
    $tc_author   = str_replace('@', '', get_the_author_meta('twitter'));
?
    meta name=twitter:card value=summary /
    meta name=twitter:site value=@elegantthemes /
    meta name=twitter:title value=?php echo $tc_title; ? /
    meta name=twitter:description value= /
    meta name=twitter:url value=?php echo $tc_url; ? /
?php global $file; ?
      meta name=twitter:image value=?php echo $file; ? / 
        ?php if($tc_author) { ?
        meta name=twitter:creator value=@?php echo $tc_author; ? / 
        ?php

    }
    }
} 

add_action('wp_head', 'add_twitter_cards');

and an AJAX call which currently shares the images to Facebook:

    $(document).on('click','.twitter',function(e){

    $.ajax({
    type: POST,
    url: ajaxurl,
    data: {
    action: 'canvasUpload',
    uploadImage: data
    }
    }).done(function(o) {
      var url = o.split('uploads');
      var fileURL =  $(#fileURL).html(url[1]);
      var imgURL = $('#imgURL').html();
      var finalURL = imgURL + $(#fileURL).html().replace(png0, png);;
      
 window.open(
          'http://www.facebook.com/sharer.php?u='+ finalURL +'',
          popupFacebook,
          width=650, height=270, resizable=0, toolbar=0, menubar=0, status=0, location=0, scrollbars=0
        );
       });
    
        return false;
    });
    });

Any help much appreciated,

Topic ajax twitter Wordpress

Category Web

About

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