I would like some advice on how to improve the code I use for allowing people to comment posts.
Users can only submit a comment if they are connected with Facebook.
I started developping this feature directly in the comments.php template. It works but there is another feature which permit people to publish a message on their wall if they tick a checkbox before sending the comment.
I have some troubles for developping this functionnality because I need an instance of the Facebook class. I already have it in my comments.php and I was wondering if there was a way to use it instead of creating a new one.
Here is the code :
comments.php:
<?php
locate_template( 'include/facebook.php', true );
$config = array();
$config['appId'] = get_option( 'appId' );
$config['secret'] = get_option( 'secret' );
$facebook = new Facebook($config);
$session = $facebook->getUser();
if(!$session){
$loginUrl = $facebook->getLoginUrl(array('scope'=>'publish_stream, email', 'redirect_uri'=>'http://www.myredirecturi.fr'));
}
if( !isset( $session ) || empty( $session ) ){
?>
<div class="btns">
<div class="fb-connect">
<a href="https://wordpress.stackexchange.com/questions/113481/<?php echo $loginUrl; ?>"><img src="<?php echo get_template_directory_uri(); ?>/img/btn-fb.png" alt=""></a>
</div>
</div>
<?php
}
$nb_coms = get_comments_number();
if( $nb_coms != 0 ){
wp_list_comments('callback=custom_comment&avatar_size=50');
}
?>
<?php
if($session){
try {
$me = $facebook->api('/me');
$username = $me['username'];
$firstname = $me['first_name'];
$email = $me['email'];
// I display here my custom comment form
}
catch(FacebookApiException $e){
error_log($e);
}
}
?>
functions.php
<?php
add_action( 'comment_post', 'custom_save_comment_data' );
function custom_save_comment_data( $comment_id ) {
add_comment_meta( $comment_id, 'fb_username', $_POST['fb_username'] );
//if( isset($_POST['publish']) ){
// $params = array(
// 'message' => "Hurray! This works :)",
// 'name' => "This is my title",
// 'caption' => "My Caption",
// 'description' => "Some Description...",
// 'link' => "http://stackoverflow.com",
// 'picture' => "http://i.imgur.com/VUBz8.png",
// );
// $user = $_POST['fb_userid'];
// $post = $facebook->api("/$user/feed","POST",$params);
//}
}
?>
What do you recommend for pass the facebook object ? Does the way I developped these features is correct ? or should I create a plugin ? if it’s the case, why ?