[PHP] URL สำหรับดึงเลข Share Facebook, Twitter

  • Update 12/2016 for Facebook code

เนื่องจากต้องทำระบบดึงเลข Facebook, Twitter Share Count เลยเขียนฟังก์ชั่นขึ้นมาใช้เองใน WordPress เอาไปใช้กันต่อได้ตามสบาย

// Get Facebook Share Count
function get_facebook_count( $url ) {
  $this_url = rawurlencode( $url );
  $json_string = file_get_contents('http://graph.facebook.com/?id=' . $this_url);
  $json = json_decode($json_string, true);
  return isset($json['share']['share_count']) ? intval($json['share']['share_count']) : 0;
}

ถ้าอยากให้เร็วต้อง Cache ด้วย อาจจะเก็บลง Transient ก็ได้ แต่งานนี้ลูกค้า Cache ที่ตัว Server เลยไม่ได้ใช้ Transient ครับ

หากต้องการเก็บใน Transient API ของ WordPress (แคชค่าตามระยะเวลาที่เราต้องการ) สามารถใช้โค้ดด้านล่างแทนได้

function get_facebook_count( $url ) {
  // Get Facebook API from Transient
  if ( false === ( $fbcount = get_transient( $url ) ) ) {
    // It wasn't there, regenerate the data and save the transient
    $this_url = rawurlencode( $url );
    $json_string = file_get_contents('http://graph.facebook.com/?id=' . $this_url);
    $json = json_decode($json_string, true);
    $fbcount = isset($json['share']['share_count']) ? intval($json['share']['share_count']) : 0;
    set_transient( 'fbshare_' . $this_url, $fbcount, HOUR_IN_SECONDS );
  }
  return $fbcount;
}

ข้อมูลเพิ่มเติม:

  • Twitter เลิกนับ Share Count URL แล้ว
  • Google+ ต้องทำ OAuth + ส่งข้อมูลไปทาง Post

Reference: https://gist.github.com/jonathanmoore/2640302, (outdated Facebook code)

http://99webtools.com/blog/php-script-to-get-social-share-count/


Posted

in

, , ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *