A volte in WordPress vi può essere la necessità di estrarre dei dati dai post e di visualizzarli separatamente. Un tipico esempio è il numero dei commenti, che possono essere estratti con uno shortcode.
Il seguente codice, da aggiungere al file functions.php
, crea lo shortcode [comments]
che accetta come parametro l'ID del post:
function comments_shortcode($atts) {
extract( shortcode_atts( array(
'id' => ''
), $atts ) );
$num = 0;
$post_id = $id;
$queried_post = get_post($post_id);
$cc = $queried_post->comment_count;
if( $cc == $num || $cc > 1 ) : $cc = $cc.' Commenti';
else : $cc = $cc.' Commento';
endif;
$permalink = get_permalink($post_id);
return '<a href="'. $permalink . '" class="comments_link">' . $cc . '</a>';
}
add_shortcode('comments', 'comments_shortcode');