2013-02-28 9 views
5

Stavo lavorando sul mio lato Word Press e ho avuto questa idea. Invece di implementare una funzionalità "Mi piace/Fav" per determinare i migliori articoli, vorrei invece contare insieme quante condivisioni di facebook, tweets e +1 che l'articolo ha ricevuto e una volta che sono tutti contati li memorizzano nel database (con l'articolo corrispondente) , quindi posso scegliere i migliori articoli selezionando quelli con più condivisioni, tweet e +1. Avrei anche bisogno di aggiornare il database ogni volta che l'utente fa clic su uno dei pulsanti facebook, twitter o g +.Contare insieme facebook, twitter e g + "condivisioni" e memorizzarli nel database?

È realizzabile all'interno di Word Press e mediante l'uso delle loro API?

risposta

8

Questo non è così semplice come sembra.

Esiste un ottimo esempio su GitHub con tutte le API che si desidera implementare: Get the share counts from various APIs.

È possibile connettersi a questi server e recuperare i dati utilizzando jQuery e AJAX:

function how_many_tweets(url, post_id) { 
    var api_url = "http://cdn.api.twitter.com/1/urls/count.json"; 
    var just_url = url || document.location.href; 
    $.ajax({ 
     url: api_url + "?callback=?&url=" + just_url, 
     dataType: 'json', 
     success: function(data) { 
      var tweets_count = data.count; 
      // do something with it 
     } 
    }); 
} 

function how_many_fb_shares(url, post_id) { 
    var api_url = "http://api.facebook.com/restserver.php"; 
    var just_url = url || document.location.href; 
    $.ajax({ 
     url: api_url + "?method=links.getStats&format=json&urls=" + just_url, 
     dataType: 'json', 
     success: function(data) { 
      var shares_count = data[0].total_count; 
      // do something with it 
     } 
    }); 
}; 

function how_many_google_pluses(url, api_key, post_id) { 
    var api_url = "https://clients6.google.com/rpc?key=" + api_key; 
    var just_url = url || document.location.href; 
    $.ajax({ 
     url: api_url, 
     dataType: 'json', 
     contentType: 'application/json', 
     type: 'POST', 
     processData: false, 
     data: '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' + just_url + '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]', 
     success: function(data) { 
      var google_pluses = data.result.metadata.globalCounts.count; 
      // do something with it 
     } 
    }) 
} 

Quindi, è possibile sostituire // do something with it linee con un'altra richiesta AJAX al tuo blog. Dovrai scrivere un plugin per gestire questa richiesta e salvare i dati nel $ wpdb. Il plugin è relativamente semplice:

<?php 

/* 
    Plugin Name: Save Share Count Request Plugin 
    Plugin URI: http://yourdomain.com/ 
    Description: This plugin catches 'save share count' requests and updates the database. 
    Version: 1.0 

*/ 

// check if request is a 'save share count' request 
// i'm using sscrp_ prefix just not to redefine another function 
// sscrp_ means SaveShareCountRequestPlugin_ 
function sscrp_is_save_share_count_request() { 
    if(isset($_GET['_save_share_count_request'])) return true; 
    else return false; 
} 

// save the count in database 
function sscrp_save_share_count_in_wpdb($type, $count, $post_id) { 

    // $count is your new count for the post with $post_id 
    // $type is your social media type (can be e.g.: 'twitter', 'facebook', 'googleplus') 
    // $post_id is post's id 

    global $wpdb; 

    // create a $wpdb query and save $post_id's $count for $type. 
    // i will not show how to do it here, you have to work a little bit 

    // return true or false, depending on query success. 

    return false; 
} 

// catches the request, saves count and responds 
function sscrp_catch_save_share_count_request() { 
    if(sscrp_is_save_share_count_request()) { 
     if(isset($_GET['type'])) { 
      $social_media_type = $_GET['type']; 
      $new_count = $_GET['value']; 
      $post_id = $_GET['post_id']; 
      if(sscrp_save_share_count_in_wpdb($social_media_type, $new_count, $post_id)) { 
       header(sprintf('Content-type: %s', 'application/json')); 
       die(json_encode(array("sscrp_saved"=>true))); 
      } else { 
       header(sprintf('Content-type: %s', 'application/json')); 
       die(json_encode(array("sscrp_saved"=>false))); 
      } 
     } else { 
      header(sprintf('Content-type: %s', 'application/json')); 
      die(json_encode(array("sscrp_saved"=>false))); 
     } 
    } 
} 

// catch the save request just after wp is loaded 
add_action('wp_loaded', 'sscrp_catch_save_share_count_request'); 

?> 

Quando hai il plugin, possiamo modificare // do something with it righe nel file JavaScript:

  1. Per how_many_tweets() sarà:

    $.ajax({ 
        url: "http://yourdomain.com/path_to_your_wp_installation/?_save_share_count_request=1&type=twitter&value=" + tweets_count + "&post_id=" + post_id, 
        dataType: 'json', 
        success: function(data) { 
         var saved = data.sscrp_saved; 
         if(saved) { 
          // done! 
         } else { 
          // oh crap, an error occured 
         } 
        } 
    }); 
    
  2. Per how_many_fb_shares() copia/incolla il codice da how_many_tweets() e cambia semplicemente:

    ... 
        url: "... &type=facebook ... 
    ... 
    
  3. Per how_many_google_pluses() fare lo stesso come con facebook:

    ... 
        url: "... &type=googleplus ... 
    ... 
    

Quindi, è necessario in qualche modo filtrare i messaggi utilizzando $type e $count che hai scritto al vostro $wpdb.


Devo andare ora. Ti ho fornito più di una semplice informazione sulla connessione alle API di Facebook, Twitter e Google. Spero che ne farai uso e realizzi ciò che desideri ottenere.

+1

Questa è stata una lettura interessante, grazie per la risposta estesa, lo accetterò e vi darò un premio +50 una volta che posso – Ilja

+1

Grazie! Sono contento di poterti aiutare. :) – akashivskyy

+0

@akashivskyy Ho una domanda per te che voglio recuperare i feed degli utenti e pubblicare dai social media e archiviare alla base di dati utilizzando le API. Per favore aiutami a risolvere questa difficoltà. – Apache

Problemi correlati