WordPress: usare OpenGraph senza rinunciare alla validazione del W3C

Come utilizzare il protocollo OpenGraph di Facebook in WordPress senza rinunciare alla validazione HTML.

WordPress di Gabriele Romanato

La difficoltà del protocollo OpenGraph di Facebook è che la sua sintassi non è compatibile con le specifiche del W3C, sollevando quindi un problema di validazione. Vediamo come ovviare a questo problema in WordPress.

Nel file functions.php è sufficiente aggiungere la seguente funzione che esegue un check sullo user-agent per individuare il validatore del W3C:


function add_opengraph_for_posts() {
  if(stristr($_SERVER['HTTP_USER_AGENT'], 'validator') === false) {
    if ( is_singular() ) {
        global $post;
        setup_postdata( $post );
        $output = '<meta property="og:type" content="article" />' . "\n";
        $output .= '<meta property="og:title" content="' . esc_attr( get_the_title() ) . '" />' . "\n";
        $output .= '<meta property="og:url" content="' . get_permalink() . '" />' . "\n";
        $output .= '<meta property="og:description" content="' . esc_attr( get_the_excerpt() ) . '" />' . "\n";
        if ( has_post_thumbnail() ) {
            $imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
            $output .= '<meta property="og:image" content="' . $imgsrc[0] . '" />' . "\n";
        }
        echo $output;
    }
  }
}
add_action( 'wp_head', 'add_opengraph_for_posts' );

Nel file header.php usiamo lo stesso approccio per inserire l'attributo prefix:


<?php
$prefix = (stristr($_SERVER['HTTP_USER_AGENT'], 'validator') === false) ? ' prefix="og: http://ogp.me/ns#" : '';
?>
<html <?php language_attributes(); ?><?php echo $prefix; ?>>