Skip to content

Instantly share code, notes, and snippets.

@sethrubenstein
Last active August 29, 2015 13:57
Show Gist options
  • Save sethrubenstein/9487249 to your computer and use it in GitHub Desktop.
Save sethrubenstein/9487249 to your computer and use it in GitHub Desktop.
Social Tools & Widget
<?php
/**
* Suite of tools and actions for social media
*
*/
$facebook_app_id = '1411050029147291';
function social_tools($tool) {
$twitter_count = get_post_meta( get_the_ID(), "_tweet_count", true );
$facebook_count = get_post_meta( get_the_ID(), "_facebook_count", true );
$google_plus_count = get_post_meta( get_the_ID(), "_gplus_count", true );
$social_total_count = get_post_meta( get_the_ID(), "_total_share_count", true );
if ( 'share_buttons' == $tool ) {
$link = get_permalink();
$twitter_share_link = 'https://twitter.com/home?status='.$link;
$facebook_share_link = 'https://www.facebook.com/sharer/sharer.php?u='.$link;
$google_plus_share_link = 'https://plus.google.com/share?url='.$link;
$markup = '
<div class="entry-social '.$tool.'">
<a class="twitter" href="'.$twitter_share_link.'">
<span class="symbol">&#xe086;</span> <span class="count">'.$twitter_count.' <strong>Tweet This</strong></span>
</a>
<a class="facebook" href="'.$facebook_share_link.'">
<span class="symbol">&#xe027;</span> <span class="count">'.$facebook_count.' <strong>Share This</strong></span>
</a>
<a class="google-plus" href="'.$google_plus_share_link.'">
<span class="symbol">&#xe039;</span> <span class="count">'.$google_plus_count.' <strong>+1 This</strong></span>
</a>
</div>';
echo $markup;
}
if ( 'social_counts' == $tool ) {
$markup = '
<div class="entry-social '.$tool.'">
<div class="twitter">
<span class="symbol">&#xe086;</span> <span class="count">'.$twitter_count.' Tweets</span>
</div>
<div class="facebook">
<span class="symbol">&#xe027;</span> <span class="count">'.$facebook_count.' Shares</span>
</div>
</div>';
echo $markup;
}
}
/**
* Display 5 most popular as calcualted by total shares posts
* hooks into Most_Shared_Widget widget. Can be found in widgets.php
*/
function most_shared_posts(){
//Modify the query before it fires to look at past 30 days only
function filter_where($where = '') {
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where');
//Begin query
$args = array(
'meta_key' => '_total_share_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'posts_per_page' => 5,
);
$most_shared_posts = new WP_Query($args);
if ( $most_shared_posts->have_posts() ) {
echo '<ul>';
while ( $most_shared_posts->have_posts() ) {
$most_shared_posts->the_post();
$twitter_count = get_post_meta( get_the_ID(), "_tweet_count", true );
$facebook_count = get_post_meta( get_the_ID(), "_facebook_count", true );
$google_plus_count = get_post_meta( get_the_ID(), "_gplus_count", true );
$social_total_count = get_post_meta( get_the_ID(), "_total_share_count", true );
$link = get_permalink();
$title = get_the_title();
echo '<li><a href="'.$link.'">'.$title.'';
echo '
<div class="social_counts">
<div class="twitter">
<span class="symbol">&#xe086;</span> <span class="count">'.$twitter_count.'</span>
</div>
<div class="facebook">
<span class="symbol">&#xe027;</span> <span class="count">'.$facebook_count.'</span>
</div>
<div class="google-plus">
<span class="symbol">&#xe039;</span> <span class="count">'.$google_plus_count.'</span>
</div>
</div>';
echo '</a></li>';
}
echo '</ul>';
} else {
echo 'No Posts Found';
}
/* Restore original Post Data */
wp_reset_postdata();
}
/**
* Loop through posts from the past week and update Facebook counts
*/
function update_facebook_counts() {
global $wpdb;
$wpdb->show_errors();
// Limit counts fetching to past week (or past day if on test platform)
$posts_cutoff = 432000;
$posts_limit = 500;
if(DEV_ENVIRONMENT) {
$posts_limit = 20;
}
$posts_start_time = time() - $posts_cutoff;
$posts_start_date = date("Y-m-d", $posts_start_time);
// Get the posts within this range
$get_recent_posts = "SELECT ID FROM " . $wpdb->prefix . "posts WHERE 1" .
" AND post_status = 'publish'" .
" AND post_type IN ('post', 'stories')" .
" AND post_date > " . $posts_start_date .
" ORDER BY post_date DESC LIMIT " . $posts_limit;
echo $get_recent_posts;
$recent_posts = $wpdb->get_results($get_recent_posts);
//TODO: Batch these requests
foreach($recent_posts AS $recent_post) {
get_facebook_count($recent_post->ID);
}
}
add_action('wp_ajax_update_facebook_counts', 'update_facebook_counts');
add_action('wp_ajax_nopriv_update_facebook_counts', 'update_facebook_counts');
// http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
// To run, http://site-address/wp-admin/admin-ajax.php?action=update_facebook_counts
/**
* Loop through posts from the past week and update Twitter counts
*/
function update_tweet_counts() {
global $wpdb;
$wpdb->show_errors();
// Limit counts fetching to past week
$posts_cutoff = 432000;
$posts_limit = 500;
if(DEV_ENVIRONMENT) {
$posts_limit = 20;
}
$posts_start_time = time() - $posts_cutoff;
$posts_start_date = date("Y-m-d", $posts_start_time);
// Get the posts within this range
$get_recent_posts = "SELECT ID FROM " . $wpdb->prefix . "posts WHERE 1" .
" AND post_status = 'publish'" .
" AND post_type IN ('post', 'stories')" .
" AND post_date > " . $posts_start_date .
" ORDER BY post_date DESC LIMIT " . $posts_limit;
echo $get_recent_posts;
$recent_posts = $wpdb->get_results($get_recent_posts);
//TODO: Batch these requests
foreach($recent_posts AS $recent_post) {
get_tweet_count($recent_post->ID);
}
}
add_action('wp_ajax_update_tweet_counts', 'update_tweet_counts');
add_action('wp_ajax_nopriv_update_tweet_counts', 'update_tweet_counts');
// http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
// To run, http://site-address/wp-admin/admin-ajax.php?action=update_tweet_counts
/**
* Loop through posts from the past week and update Google Plus counts
*/
function update_total_share_counts() {
global $wpdb;
$wpdb->show_errors();
// Limit counts fetching to past week (or past day if on test platform)
$posts_cutoff = 432000;
$posts_limit = 500;
if(DEV_ENVIRONMENT) {
$posts_limit = 20;
}
$posts_start_time = time() - $posts_cutoff;
$posts_start_date = date("Y-m-d", $posts_start_time);
// Get the posts within this range
$get_recent_posts = "SELECT ID FROM " . $wpdb->prefix . "posts WHERE 1" .
" AND post_status = 'publish'" .
" AND post_type IN ('post', 'stories')" .
" AND post_date > " . $posts_start_date .
" ORDER BY post_date DESC LIMIT " . $posts_limit;
echo $get_recent_posts;
$recent_posts = $wpdb->get_results($get_recent_posts);
//TODO: Batch these requests
foreach($recent_posts AS $recent_post) {
get_total_social_count($recent_post->ID);
}
}
add_action('wp_ajax_update_total_share_counts', 'update_total_share_counts');
add_action('wp_ajax_nopriv_update_total_share_counts', 'update_total_share_counts');
// http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
// To run, http://site-address/wp-admin/admin-ajax.php?action=update_total_share_counts
/**
* Loop through posts from the past week and update Google Plus counts
*/
function update_gplus_counts() {
global $wpdb;
$wpdb->show_errors();
// Limit counts fetching to past week (or past day if on test platform)
$posts_cutoff = 432000;
$posts_limit = 500;
if(DEV_ENVIRONMENT) {
$posts_limit = 20;
}
$posts_start_time = time() - $posts_cutoff;
$posts_start_date = date("Y-m-d", $posts_start_time);
// Get the posts within this range
$get_recent_posts = "SELECT ID FROM " . $wpdb->prefix . "posts WHERE 1" .
" AND post_status = 'publish'" .
" AND post_type IN ('post', 'stories')" .
" AND post_date > " . $posts_start_date .
" ORDER BY post_date DESC LIMIT " . $posts_limit;
echo $get_recent_posts;
$recent_posts = $wpdb->get_results($get_recent_posts);
//TODO: Batch these requests
foreach($recent_posts AS $recent_post) {
get_gplus_count($recent_post->ID);
}
}
add_action('wp_ajax_update_gplus_counts', 'update_gplus_counts');
add_action('wp_ajax_nopriv_update_gplus_counts', 'update_gplus_counts');
// http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
// To run, http://site-address/wp-admin/admin-ajax.php?action=update_gplus_counts
/**
* Retrieve the Facebook Graph data for an individual post
*/
function get_facebook_count($post_id) {
// Since Facebook doesn't track likes on our test instances, we'll get these numbers for the live site posts
$post_url = get_permalink($post_id);
if(DEV_ENVIRONMENT) {
$post_url = str_replace(get_bloginfo('url'), "http://DOMAINHERE", $post_url);
}
// Grab the facebook count for this post
$url = "http://graph.facebook.com/" . $post_url;
$starttime = microtime(true);
$s = curl_init();
curl_setopt($s,CURLOPT_URL, $url);
curl_setopt($s,CURLOPT_HEADER,false);
curl_setopt($s,CURLOPT_RETURNTRANSFER,1);
curl_setopt($s, CURLOPT_TIMEOUT, 5);
$result = curl_exec($s);
curl_close( $s );
$endtime = microtime(true);
$duration = $endtime - $starttime;
// error_log("Facebook curl execution time: " . $duration);
$obj = json_decode($result, true);
if(!($obj && $obj["error"] == 0)){
error_log("social-counts-tool: Facebook response: " . var_export($obj, true));
} else {
$facebook_count = $obj["shares"];
if((!empty($facebook_count)) && $facebook_count != 0){
// If this post has Facebook shares, note them in wp_postmeta
update_post_meta($post_id, "_facebook_count", $facebook_count);
} else {
update_post_meta($post_id, "_facebook_count", '0');
}
}
// Use following line to debug
// error_log("Post #". $post_id ." has " . $facebook_count . " shares.");
}
/**
* Retrieve the Twitter data for an individual post
*/
function get_tweet_count($post_id) {
// Again, getting these numbers for the live site posts
$post_url = get_permalink($post_id);
if(DEV_ENVIRONMENT) {
$post_url = str_replace(get_bloginfo('url'), "http://DOMAINHERE", $post_url);
}
// Grab the tweet count for this post
$url = "https://cdn.api.twitter.com/1/urls/count.json?url=" . $post_url;
$starttime = microtime(true);
$s = curl_init();
curl_setopt($s,CURLOPT_URL, $url);
curl_setopt($s,CURLOPT_HEADER,false);
curl_setopt($s,CURLOPT_RETURNTRANSFER,1);
curl_setopt($s, CURLOPT_TIMEOUT, 5);
$result = curl_exec($s);
curl_close( $s );
$endtime = microtime(true);
$duration = $endtime - $starttime;
// error_log("Twitter curl execution time: " . $duration);
$obj = json_decode($result, true);
if(!($obj && $obj["error"] == 0)){
error_log("social-counts-tool: Twitter response: " . var_export($obj, true));
} else {
$tweet_count = $obj["count"];
if((!empty($tweet_count)) && $tweet_count != 0){
// If this post has retweets, note them in wp_postmeta
update_post_meta($post_id, "_tweet_count", $tweet_count);
} else {
update_post_meta($post_id, "_tweet_count", '0');
}
}
// Use following line to debug
// error_log("Post #". $post_id ." has " . $tweet_count . " tweets.");
}
/**
* Retrieve the Google Plus data for an individual post
*/
function get_gplus_count($post_id) {
// Since Google Plus doesn't track likes on our test instances, we'll get these numbers for the live site posts
$post_url = get_permalink($post_id);
if(DEV_ENVIRONMENT) {
$post_url = str_replace(get_bloginfo('url'), "http://DOMAINHERE", $post_url);
}
// Grab the google plus count for this post
$url = "https://clients6.google.com/rpc";
$starttime = microtime(true);
$s = curl_init();
curl_setopt($s,CURLOPT_URL, $url);
curl_setopt($s,CURLOPT_POST, true);
curl_setopt($s, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($s, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"'.rawurldecode($post_url).'","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
curl_setopt($s,CURLOPT_RETURNTRANSFER,1);
curl_setopt($s, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($s, CURLOPT_TIMEOUT, 5);
$result = curl_exec($s);
curl_close( $s );
$endtime = microtime(true);
$duration = $endtime - $starttime;
// error_log("Google Plus curl execution time: " . $duration);
$obj = json_decode($result, true);
if(!($obj && $obj["error"] == 0)){
error_log("social-counts-tool: Google Plus response: " . var_export($obj, true));
} else {
$gplus_count = $obj[0]['result']['metadata']['globalCounts']['count'];
if((!empty($gplus_count)) && $gplus_count != 0){
// If this post has Google +1s, note them in wp_postmeta
update_post_meta($post_id, "_gplus_count", $gplus_count);
} else {
update_post_meta($post_id, "_gplus_count", '0');
}
}
// Use following line to debug
//error_log("Post #". $post_id ." has " . $gplus_count . " Google +1s.");
}
function get_total_social_count($post_id) {
$twitter_count = get_post_meta( $post_id, "_tweet_count", true );
$facebook_count = get_post_meta( $post_id, "_facebook_count", true );
$google_plus_count = get_post_meta( $post_id, "_gplus_count", true );
//Calculate
$total_count = ($twitter_count + $facebook_count + $google_plus_count);
//Add meta value
update_post_meta( $post_id, "_total_share_count", $total_count );
}
/**
* Facebook & Twitter Social Metadata
* @return markup to wp_head hook
*/
function get_social_metadata() {
if ( is_single() ) {
$title = esc_html( get_the_title() );
$link = esc_html( get_permalink() );
$description = esc_html( get_the_excerpt() );
$image_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) );
$image = $image_src[0];
//Facebook Specific
$fb_type = 'article';
} else {
$title = get_bloginfo('name');
$link = esc_html( get_bloginfo('url') );
$image = 'your default image path here';
//Facebook Specific
$fb_type = 'website';
}
/**
* Facebook
*/
$fb_app_id = $GLOBALS['facebook_app_id'];
$fb_url = esc_html( get_bloginfo('url') );
$fb_metatext = "";
$fb_metatext .= '<meta property="fb:admins" content="100001364918392"/>' . "\n";
$fb_metatext .= '<meta property="fb:app_id" content="' . $fb_app_id . '" />' . "\n";
$fb_metatext .= '<meta property="og:url" content="' . $fb_url . '" />' . "\n";
$fb_metatext .= '<meta property="og:type" content="'.$fb_type.'" />' . "\n";
$fb_metatext .= '<meta property="og:description" content="' . $description . '"/>' . "\n";
$fb_metatext .= '<meta property="og:image" content="' . $image . '" />' . "\n";
$fb_metatext .= '<meta property="og:title" content="' . $title . '" />' . "\n";
echo $fb_metatext;
/**
* Twitter
*/
$tw_metatext = "";
$tw_metatext .= '<meta name="twitter:card" content="summary" />' . "\n";
$tw_metatext .= '<meta name="twitter:site" content="@HalfInTen" />' . "\n";
$tw_metatext .= '<meta name="twitter:title" content="' . $title . '" />' . "\n";
$tw_metatext .= '<meta name="twitter:description" content="' . $description . '" />' . "\n";
$tw_metatext .= '<meta name="twitter:image" content="' . $image . '" />' . "\n";
echo $tw_metatext;
}
add_action( 'wp_head', 'get_social_metadata' );
function get_facebook_code() {
$fb_app_id = $GLOBALS['facebook_app_id'];
$markup = <<<EOT
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '$fb_app_id', // App ID from the App Dashboard
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
xfbml : true // parse XFBML tags on this page?
});
};
(function(d, debug){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
</script>
EOT;
echo $markup;
}
add_action( 'wp_head', 'get_facebook_code' );
function get_facebook_comments() {
global $post;
$comment_url = get_permalink($post->ID);
$comment_code = '
<a name="comment_link"></a>
<p class="comment-disclaimer">YOUR DISCLAIMER HERE.</p>
<div id="fb-comments">
<fb:comments href="'.$comment_url.'" num_posts="10"></fb:comments>
</div>';
echo $comment_code;
}
?>
<?php
/**
* Add Most Shared Posts Widget
*/
class Most_Shared_Widget extends WP_Widget {
/**
* Register widget with WordPress.
*/
function __construct() {
parent::__construct(
'most-shared-posts', // Base ID
__('Most Shared Posts', 'text_domain'), // Name
array( 'description' => __( 'Show most shared posts', 'text_domain' ), ) // Args
);
}
/**
* Front-end display of widget.
*
* @see WP_Widget::widget()
*
* @param array $args Widget arguments.
* @param array $instance Saved values from database.
*/
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
echo $args['before_widget'];
if ( ! empty( $title ) ) {
echo $args['before_title'] . $title . $args['after_title'];
}
most_shared_posts();
echo $args['after_widget'];
}
/**
* Back-end widget form.
*
* @see WP_Widget::form()
*
* @param array $instance Previously saved values from database.
*/
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'Most Shared Posts', 'text_domain' );
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
/**
* Sanitize widget form values as they are saved.
*
* @see WP_Widget::update()
*
* @param array $new_instance Values just sent to be saved.
* @param array $old_instance Previously saved values from database.
*
* @return array Updated safe values to be saved.
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // class Most_Shared_Widget
/**
* Register all of our widgets
*/
function register_social_widget() {
register_widget( 'Most_Shared_Widget' );
}
add_action( 'widgets_init', 'register_social_widget' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment