Inserire il numero di condivisioni su Facebook nei post e nelle pagine di WordPress si rivela come un'operazione alquanto semplice.
Definiamo il seguente codice in functions.php
:
function my_get_shares_count( $url ) {
$base_url = 'http://graph.facebook.com/?id=';
$shares = '0';
if( filter_var( $url, FILTER_VALIDATE_URL ) ) {
$api_url = $base_url . $url;
$response = wp_remote_get( $api_url, array( 'timeout' => 2 ) );
if ( !is_wp_error( $response ) ) {
$json = json_decode( $response['body'] );
if( $json->shares ) {
$shares = $json->shares;
}
}
}
return $shares;
}
function my_shares() {
global $post;
$permalink = get_permalink( $post->ID );
$shares_count = my_get_shares_count( $permalink );
$html = '<span class="shares">' . $shares_count . '</span>';
return $html;
}
add_shortcode( 'my-shares', 'my_shares' );
Abbiamo creato il seguente shortcode:
[my-shares]
Dato che la funzione principale non accetta parametri, possiamo anche inserirla direttamente nel nostro tema:
<?php echo my_shares(); ?>