Last active
October 11, 2018 15:17
-
-
Save SapporoTK/db9e561c01298e55cca95ecf501a2892 to your computer and use it in GitHub Desktop.
[WordPress] add JSON-LD for schema.org
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
©planet-green.com | |
*/ | |
function insert_json_ld_for_schema_org() | |
{ | |
if( !is_single() || !have_posts() ) { | |
return; | |
} | |
//あなたのサイトのロゴ画像をここで設定してください | |
$logo = array( | |
'@type' => 'ImageObject', | |
'url' => 'http://*****/****.jpg', | |
'width' => '240', | |
'height' => '80' | |
); | |
while (have_posts()) { | |
the_post(); | |
$category_info = get_the_category(); | |
if( count($category_info) > 1 ) { | |
$articleSection = array(); | |
foreach( $category_info as $ct ) | |
{ | |
$articleSection[] = $ct->name; | |
} | |
} else { | |
$articleSection = $category_info[0]->name; | |
} | |
//添付画像を取得 | |
$attachments = get_children( array( 'post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image') ); | |
$images = array(); | |
foreach($attachments as $image) { | |
$src = wp_get_attachment_image_src( $image->ID, 'medium' ); | |
$images[] = array( | |
'@type' => 'ImageObject', | |
'url' => $src[0], | |
'width' => strval($src[1]), | |
'height' => strval($src[2]) | |
); | |
} | |
//添付画像が無い場合はアイキャッチ画像を取得 | |
if( !count($images) ) { | |
if( has_post_thumbnail() ) { | |
$thumbnail_id = get_post_thumbnail_id(); | |
$src = wp_get_attachment_image_src( $thumbnail_id , 'medium' ); | |
$images = array( | |
'@type' => 'ImageObject', | |
'url' => $src[0], | |
'width' => strval($src[1]), | |
'height' => strval($src[2]) | |
); | |
} else { | |
//それも無い場合はロゴ画像をセット | |
$images = $logo; | |
} | |
} | |
$data = array( | |
'@context' => 'http://schema.org', | |
'@type' => 'Article', | |
'headline' => get_the_title(), | |
'author' => array( | |
'@type' => 'Person', | |
'name' => get_the_author(), | |
), | |
'datePublished' => get_the_date('Y-m-d'), | |
'dateModified' => get_the_modified_time( 'Y-m-d' ), | |
'articleSection' => $articleSection, | |
'url' => get_permalink(), | |
'mainEntityOfPage' => array( | |
'@type' => 'WebPage', | |
'@id' => get_permalink() | |
), | |
'publisher' => array( | |
'@type' => 'Organization', | |
'name' => get_bloginfo('name'), | |
'logo' => $logo, | |
), | |
'image' => $images, | |
); | |
//php5.4以前のバージョンではオプション引数(JSON_UNESCAPED〜)を削除すれば大丈夫だと思います。 | |
echo '<script type="application/ld+json">' | |
.json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT) | |
.'</script>'.PHP_EOL; | |
} | |
rewind_posts(); | |
} | |
add_action('wp_head','insert_json_ld_for_schema_org'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment