###前提・実現したいこと
// JSON-LD
add_action('wp_head','insert_json_ld');
function insert_json_ld (){
if (have_posts()) : while (have_posts()) : the_post();
$context = 'http://schema.org';
$type = 'Article';
$headline = get_the_title();
$authorType = 'Person';
$authorName = get_the_author();
$dataPublished = get_the_date('c');
$thumbnail_id = get_post_thumbnail_id($post->ID);
$image = wp_get_attachment_image_src( $thumbnail_id, 'full' );
$imageurl = $image[0];
$category_info = get_the_category();
$articleSection = $category_info[0]->name;
$articleBody = get_the_content();
$url = get_permalink();
$publisherType = 'Organization';
$publisherName = get_bloginfo('name');
$json= " \"@context\" : \"{$context}\", \"@type\" : \"{$type}\", \"headline\" : \"{$headline}\", \"author\" : { \"@type\" : \"{$authorType}\", \"name\" : \"{$publisherName}\" }, \"datePublished\" : \"{$dataPublished}\", \"dateModified\" : \"{$dataPublished}\", \"mainEntityOfPage\": { \"@type\": \"WebPage\", \"@id\": \"{$url}\" }, \"image\" : { \"@type\" :\"ImageObject\", \"url\" :\"{$imageurl}\", \"height\" :\"400\", \"width\" :\"400\" }, \"articleSection\" : \"{$articleSection}\", \"url\" : \"{$url}\", \"publisher\" : { \"@type\" : \"{$publisherType}\", \"name\" : \"{$publisherName}\", \"logo\" :{ \"@type\" : \"ImageObject\", \"url\" : \"http://hogehoge.com/images.png\" } } "; echo '<script type="application/ld+json">{'.$json.'}</script>'; endwhile; endif; rewind_posts(); }
ワードプレスのfunction関数に上記を記述すると、グーグルに対して構造化を定義できるのですが、これだと、アイキャッチを登録しておかないと画像URLが表示されず、構造化エラーとなってしまいます。
上記より抜粋
ここの所
"image" : {
"@type" :"ImageObject",
"url" :"{$imageurl}",
"height" :"400",
"width" :"400"
},
の、 "url" :"{$imageurl}", の所なんですが、これだとアイキャッチがあれば、画像URLがでてもんだいないのですが、
アイキャッチを登録していない記事の場合は画像URLが挿入されずグーグルから構造化エラーとなってしまいます。
アイキャッチが無い時だけデフォルトで固有の画像URLを表示する分岐を含む書き方を教えてほしいです。
あなたの回答
tips
プレビュー