Home / Admin / Add author name to article schema if its missing
Duplicate Snippet

Embed Snippet on Your Site

Add author name to article schema if its missing

This snippet adds the author's name and author schema type to the article schema if it's missing. Given the condition set in line 3, the snippet works only on Posts.

<10
Code Preview
php
<?php
add_filter( 'aioseo_schema_output', 'add_author_name_when_missing' );
function add_author_name_when_missing( $schema ) {	
	if ( is_single() && 'post' == get_post_type() ) {
		global $post;
		$author_id = $post->post_author;
		$author_name = get_the_author_meta( 'display_name', $author_id );
		foreach ( $schema as &$schemaItem ) {
			if ( isset($schemaItem['@type']) && 'Article' === $schemaItem['@type'] ) {
				if(!isset($schemaItem['author']['name']) || !isset($schemaItem['author']['@type'])){
					$schemaItem['author']['@type'] = 'Person';
					$schemaItem['author']['name'] = $author_name;
				}
			}
		}
	}
	return $schema;
}

Comments

Add a Comment