Shoora
10/11/2018 - 3:17 PM

[WordPress] add JSON-LD for schema.org

[WordPress] add JSON-LD for schema.org

<?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');