Đếm lượt chia sẻ lên Facebook qua URL

WORDPRESS HTTP API EXAMPLE

/**
 * Display number of shares using WordPress HTTP API
 *
 * @param integer $post_id We want to get number of shares of the post with this ID
 */
function wp_get_shares( $post_id ) {
	$cache_key = 'misha_share' . $post_id;
	$access_token = 'APP_ID|APP_SECRET';
	$count = get_transient( $cache_key ); // try to get value from WordPress cache
 
	// if no value in the cache
	if ( $count === false ) {
		$response = wp_remote_get('https://graph.facebook.com/v2.7/?id=' . urlencode( get_permalink( $post_id ) ) . '&access_token=' . $access_token );
		$body = json_decode( $response['body'] );
		//print_r($body);
 
		$count = intval( $body->share->share_count );
		set_transient( $cache_key, $count, 3600 ); // store value in cache for a 1 hour
	}
	return $count;
}
echo wp_get_shares( 355 );

 

CURL EXAMPLE

/**
 * Display number of shares using PHP cURL library
 *
 * @param string $url ID We want to get number of shares of this URL
 */
function curl_get_shares( $url ){
	$access_token = 'APP ID|APP SECRET';
	$api_url = 'https://graph.facebook.com/v2.7/?id=' . urlencode( $url ) . '&access_token=' . $access_token;
	$fb_connect = curl_init(); // initializing
	curl_setopt( $fb_connect, CURLOPT_URL, $api_url );
	curl_setopt( $fb_connect, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
	curl_setopt( $fb_connect, CURLOPT_TIMEOUT, 20 );
	$json_return = curl_exec( $fb_connect ); // connect and get json data
	curl_close( $fb_connect ); // close connection
	$body = json_decode( $json_return );
	return intval( $body->share->share_count );
}
echo curl_get_shares( 'https://rudrastyh.com/api/get-facebook-shares.html' );

 

JQUERY EXAMPLE WITH LIVE DEMO

 
var token = 'APP ID|APP SECRET', // learn how to obtain it above
url = 'YOUR URL';
 
$.ajax({
	url: 'https://graph.facebook.com/v2.7/',
	dataType: 'jsonp',
	type: 'GET',
	data: {access_token: token, id: url},
	success: function(data){
 		console.log(data);
 		$('body').append(data.share.share_count);
	},
	error: function(data){
		console.log(data); // send the error notifications to console
	}
});
 
 
 

Thêm bình luận
1 Trả lời

ngon ròi

Lv1 Đã trả lời on 01/06/2018.
Thêm bình luận

Trả lời của bạn

Bằng cách gửi bài trả lời của bạn, bạn đồng ý với Chính sách bảo mậtđiều khoản dịch vụ.