最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ajax - Dynamic Twitter card images

programmeradmin0浏览0评论

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(
          '.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,

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论