WordPress Plugin Tutorial – Most shared/popular articles on facebook

To implement most shared url of any wordpress blog, first of all download facebook php sdk here Some basic setup already explained there.

wp_most_popular

Basic setup for write wordpress plugin

  • Create your plugin directoy and file with same name.
    i.e. Directory: MostPopular and File: MostPopular.php inside MostPopular direcotory.
  • Place base_facebook.php, fb_ca_chain_bundle.crt and facebook.php within the directory.
# your plugin directory
..
.
facebook.php
fb_ca_chain_bundle.crt
base_facebook.php
MostPopular.php

Start coding plugin in MostPopular.php with plugin info.

/*
Plugin Name: Most Liked Posts on Facebook
Plugin URI: https://www.vikaskbh.com/
Description: Fetches and Display most Liked urls on facebook
Version: 1.0.0
Author: Vikas Bhagwagar
Author URI: https://www.vikaskbh.com/
*/

It’s possible many other wordpress plugins may already using facebook sdk and initialized by them. So there might be class collision issue. (i.e. class re-declare error) To avoid this situation you could use php namespaces that we already discussed here. Otherwise, You could also check, if class already initialize by other plugins or not?

if(!class_exists('FacebookApiException')) {
  include_once(plugin_dir_path(__FILE__) . 'facebook.php');
}

Now initialize your widget class by extending wordpress WP_Widget class

class MostPopular extends WP_Widget {
	function MostPopular() {
		parent::WP_Widget(false, 'Popular on Facebook');
	}
}

Register your widget with wordpress framework.

function register_MostPopular(){
	register_widget('MostPopular');
}

add_action( 'widgets_init', 'register_MostPopular' );

WordPress will call our class ‘MostPopular‘ and initialize its constructor and then look for widget() function to draw widget (HTML/CSS) in frontend. (Why?)

Adding widget() function within our class.

function widget($args, $instance) {
		$args['title'] = $instance['title']; 
		plugin_popularPosts($args);  
	}
function plugin_popularPosts(){

	global $wpdb;  

	$site_urls = Array();
	$links = Array();

    $request = 'SELECT ID,post_title FROM ' . $wpdb->posts . ' WHERE post_status="publish" and post_type="post" and post_parent=0 order by ID desc' ;
	$posts = $wpdb->get_results($request);  

	foreach($posts as $key=>$value){
	$link = get_permalink($value->ID);
	$links[get_permalink($value->ID)] = $value->post_title;
	$site_urls[] = "\"".get_permalink($value->ID)."\"";

	}

	if(get_option("plugin_fb_count_data") == ""){
		do_this_hourly();
	}

	$result = unserialize(get_option("plugin_fb_count_data"));

	if(get_option("plugin_widget_title") != ""){
		$title = get_option("plugin_widget_title");
	} else {
		$title = "Popular on Facebook";
	}

	echo '<h2 style="clear:both">'.$title.'</h2>';
	echo "<ul style='padding-top:5px;margin-left:0 !important'>";
	foreach($result as $key=>$value){
		echo "<li style='margin-bottom:5px !important;clear:both;overflow:hidden;padding:3px 0 3px 0;border-bottom:1px dotted #CDCDCD'>";
		echo '<div style="float:left;width:50px;" class="fb-like" data-href="'.$value['url'].'" data-send="false" data-layout="box_count" data-width="50" data-show-faces="false" data-font="arial"></div>';
		echo "<div style='float:left;width:220px;padding-left:5px'><a href='".$value['url']."'>".$links[$value['url']]."</a></div>";
		echo "</li>";
	}
	echo "</ul>";

}

Admin Area:-

Widget Customization. Add form() & update() function in your widget. (why?)

function form($instance) {
		// outputs the options form on admin
		if ( isset( $instance[ 'title' ] ) ) {
			$title = $instance[ 'title' ];
		}
		else {
			$title = __( 'Popular on Facebook', 'plugin_widget' );
		}
		if ( isset( $instance[ 'count' ] ) ) {
			$count = $instance[ 'count' ];
		}
		else {
			$count = __( '5', 'plugin_widget' );
		}
		if ( isset( $instance[ 'skip_urls' ] ) ) {
			$skip_urls = $instance[ 'skip_urls' ];
		}
		else {
			$skip_urls = __( '', 'plugin_widget' );
		}
		?>
		<p>
		<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Widget 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>
		<p>
		<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( 'Number of Posts to be displayed:' ); ?></label> 
		<input class="widefat" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" type="text" value="<?php echo esc_attr( $count ); ?>"  />
		</p>
		<p>
		<label for="<?php echo $this->get_field_id( 'skip_urls' ); ?>"><?php _e( 'List of urls to be Ommited<br/>(seprated by lines):' ); ?></label> 
		<textarea class="widefat" style="height:150px" id="<?php echo $this->get_field_id( 'skip_urls' ); ?>" name="<?php echo $this->get_field_name( 'skip_urls' ); ?>"   ><?php echo esc_attr( $skip_urls ); ?></textarea>
		</p>
		<?php 
	}
function update($new_instance, $old_instance) {
		// processes widget options to be saved
		update_option("plugin_skip_urls",$new_instance['skip_urls']); 
		update_option("plugin_widget_title",$new_instance['title']); 
		update_option("plugin_row_count",$new_instance['count']); 
		return $new_instance;
	}
Now time to add facebook api javascript in your wordpress.
function plugin_scripts_load()  
{  
    // Deregister the included library  
    wp_deregister_script( 'plugin_fblike' );        
    // Register the library again
    wp_register_script( 'plugin_fblike', 'http://connect.facebook.net/en_US/all.js#xfbml=1&appId=000000000000', array(), null, false );  
      // replace 000000000000 with your app_id
    // For either a plugin or a theme, you can then enqueue the script: 
    wp_enqueue_script( 'plugin_fblike' ); 
} 
add_action( 'wp_enqueue_scripts', 'plugin_scripts_load' );

Fetching and storing most liked posts using Facebook API

function do_this_hourly() {

	if(!class_exists("Facebook")) {
		include_once(plugin_dir_path(__FILE__) . 'facebook.php');
	}
	global $wpdb;  
	$site_urls = Array();
	$links = Array();

    $request = 'SELECT ID,post_title FROM ' . $wpdb->posts . ' WHERE post_status="publish" and post_type="post" and post_parent=0 order by ID desc' ;
	$posts = $wpdb->get_results($request);  

	if(get_option("plugin_skip_urls") == ""){
		$skip_urls_array = Array();
	} else {
		$skip_urls_array = preg_split("/\n|\r\n/",get_option("plugin_skip_urls"));
	}

	foreach($posts as $key=>$value){
	$link = get_permalink($value->ID);
	$links[get_permalink($value->ID)] = $value->post_title;
	$site_urls[] = "\"".get_permalink($value->ID)."\"";
	}

	if(count($skip_urls_array) > 0){
		foreach($skip_urls_array as $key=>$value){

			$key_to_remove = array_search("\"".$value."\"", $site_urls);

			if (false !== $key_to_remove) {
				unset($site_urls[$key_to_remove]);
			}
		}
	}

//Get Facebook SDK Object
	$config = array(
	  'appId'  => "000000000000",
	  'secret' => "0000000000000000000000000000000",
	  'cookie' => true,
	);

	 try {
        $facebook = new Facebook($config);
    }
    catch (FacebookApiException $e) {
      //  echo 'Excetption is' . $e->__toString();
    }

	if(get_option("plugin_row_count") == ""){
		$limit_count = 5;
	} else {
		$limit_count = get_option("plugin_row_count");
	}

	$req =  "select url,total_count from link_stat where url in(".implode(",",$site_urls).") order by total_count desc limit $limit_count";

	//Create Query
	$params = array(
	    'method' => 'fql.query',
	    'query' => $req ,
	);

	$result = $facebook->api($params);
	$data = serialize($result);
	update_option("plugin_fb_count_data",$data); 

}

Call this function() hourly using wordpress scheduler.

wp_schedule_event(time(), 'hourly', 'hourly_event');
add_action('hourly_event', 'do_this_hourly');
Making plugin more graceful.

Use plugin activation and deactivation hook to start and stop wordpress cron jobs using register_activation_hook() and register_deactivation_hook() whenever user activate or deactivate the plugin.

register_activation_hook(__FILE__, 'activation');
register_deactivation_hook( __FILE__, 'deactivate' );
add_action('hourly_event', 'do_this_hourly');

function activation() {
	update_option("plugin_fb_count_data",""); 
	wp_schedule_event(time(), 'hourly', 'hourly_event');
}

function deactivate() {
	wp_clear_scheduled_hook('hourly_event');
}
Total
0
Shares
Leave a Reply

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

 
Previous Post

Flowplayer jQuery Plugin – resume from the last played position

Next Post

Beginner Tutorial – Introduction to CSS3 transitions and making it reusable using lessjs

Related Posts