php [WordPress]为schema.org添加JSON-LD

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php [WordPress]为schema.org添加JSON-LD相关的知识,希望对你有一定的参考价值。

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

以上是关于php [WordPress]为schema.org添加JSON-LD的主要内容,如果未能解决你的问题,请参考以下文章

PHP RSS转换为HTML - Wordpress

PHP 为Wordpress主题启用帖子缩略图

PHP 为wordpress角色添加功能

php 将wordpress的catogories显示为列表

PHP WordPress条件为主页SlideDeck主题代码片段

linux12 - dockerfile03 --> 搭建 PHP+Nginx+Wordpress.