JSON-LDを実装するのに、「Markup (JSON-LD) structured in schema.org」というプラグインを使おうと思っていろいろ試したのですが、何かと衝突しているっぽく記事の部分だけ出力されませんでした・・・
ということでいろいろ調べて、自分で実装してみました。
以下のソースをfunctions.phpに貼り付けると実装される(はず)
// 記事用JSON-LD
add_action('wp_head','insert_json_ld_article');
function insert_json_ld_article (){
if (is_single()) {
if (have_posts()) : while (have_posts()) : the_post();
// 設定
$context = 'http://schema.org';
$type = 'BlogPosting';
$name = get_the_title();
$authorType = 'Person';
$authorName = get_the_author();
$dataPublished = get_the_date('Y-n-j');
$dateModified = get_the_modified_time('Y-n-j');
$thumbnail_id = get_post_thumbnail_id($post->ID);
// ↓ご自身で設定ください
$imageLogo = 'http://example.com/wp-content/uploads/2016/03/logo.png';
$category_info = get_the_category();
$articleSection = $category_info[0]->name;
$articleBody = get_the_content();
$url = get_permalink();
$publisherType = 'Organization';
$publisherName = get_bloginfo('name');
$image = wp_get_attachment_image_src( $thumbnail_id, 'full' );
$imageurl = $image[0];
// サムネイルが取れなかった場合に、文中の最初の写真をセット
if(!$imageurl){
$imageurl = catch_that_image();
}
// 文中の最初の画像も取れなかった場合に、上記で設定したロゴをセット
if(!$imageurl){
$imageurl = $imageLogo;
}
// 画像の大きさを取得する
$imginfo = getimagesize($imageurl);
$imagewidth = $imginfo[0];
$imageheight = $imginfo[1];
// ロゴ画像の大きさを取得する
$imginfoLogo = getimagesize($imageLogo);
$imagewidthLogo = $imginfoLogo[0];
$imageheightLogo = $imginfoLogo[1];
$json= "
\"@context\" : \"{$context}\",
\"@type\" : \"{$type}\",
\"mainEntityOfPage\" : {
\"@type\" : \"WebPage\",
\"url\" : \"{$url}\"
},
\"headline\" : \"{$name}\",
\"author\" : {
\"@type\" : \"{$authorType}\",
\"name\" : \"{$authorName}\"
},
\"datePublished\" : \"{$dataPublished}\",
\"dateModified\" : \"{$dateModified}\",
\"image\" : {
\"@type\" : \"imageObject\",
\"url\" : \"{$imageurl}\",
\"width\" : {$imagewidth},
\"height\" : {$imageheight}
},
\"articleSection\" : \"{$articleSection}\",
\"publisher\" : {
\"@type\" : \"{$publisherType}\",
\"name\" : \"{$publisherName}\",
\"logo\" : {
\"@type\" : \"imageObject\",
\"url\" : \"{$imageLogo}\",
\"width\" : {$imagewidthLogo},
\"height\" : {$imageheightLogo}
}
}
";
echo '<script type="application/ld+json">{'.$json.'}</script>';
endwhile; endif;
rewind_posts();
}
}
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
return $first_img;
}
BlogPostingなど、ベタ書きで書いてあるところは基本的に好きなものに変更していただいていいかと思います。
うまくいってるかの確認はこちらで。
Structured Data Testing Tool | Google Developers
コチラを参考にさせていただきました。
【コピペでできる!】WordPressにschema.org(JSON-LD)を実装する方法 | Adlib
WordPress(ワードプレス)で記事の一番最初の画像を取得する方法 | 株式会社LIG


コメント