Extending Yoast To Add Your Custom Schema With Pieces

In this blog we will learn about how to extend the Yoast to output our Custom Yoast Schema Pieces.

<?php
/**
 * Schema
 *
 * @package VenuesLive
 */

namespace MyPlugin;

use Yoast\WP\SEO\Generators\Schema\Abstract_Schema_Piece;

/**
 * Class Review.
 */
class Review extends Abstract_Schema_Piece {
	/**
	 * A value object with context variables.
	 *
	 * @var WPSEO_Schema_Context
	 */
	public $context;

	/**
	 * Identifier for custom schema node.
	 *
	 * @var string
	 */
	public $identifier = 'my_review_schema';

	/**
	 * Review constructor.
	 *
	 * @param WPSEO_Schema_Context $context Value object with context variables.
	 */
	public function __construct( \WPSEO_Schema_Context $context ) {
		$this->context = $context;
	}

	/**
	 * Determines whether or not a piece should be added to the graph.
	 *
	 * @return bool
	 */
	public function is_needed() {

		if ( ! empty( $this->context->post ) && REVIEW_POST_TYPE_SLUG === $this->context->post->post_type && is_singular() ) {
			return true;
		}

		return false;
	}

	/**
	 * Add review piece of the graph.
	 *
	 * @return mixed
	 */
	public function generate() {
		$data = [];

    $the_post_id = $$this->context->id; // This will contain post Id.

		$event_schema = [
			'@id'   => 23,
			'@type' => $the_post_id, 
			'name'        => $this->context->title,
			'description' => wp_strip_all_tags( get_the_content( $the_post_id ) ),
      'dateCreated' => $this->helpers->date->format( get_the_date( $the_post_id ) ),
      'url'         => get_the_permalink( $the_post_id ),
		];

		$data[] = $event_schema;

		return $data;

	}


}

You can get more details about what you fields require in the schema by searching it here

Now let’s instantiate the above Review Class

add_filter( 'wpseo_schema_graph_pieces', __NAMESPACE__ . '\\yoast_add_graph_pieces', 11, 2 );

/**
 * Adds Schema pieces to our output.
 *
 * @param array                 $pieces  Graph pieces to output.
 * @param \WPSEO_Schema_Context $context Object with context variables.
 *
 * @return array Graph pieces to output.
 */
function yoast_add_graph_pieces( $pieces, $context ) {
	$pieces[] = new Review( $context );

	return $pieces;
}

Now Check the JSON LD in your single post src, it would have outputted that in the existing JSON+LD Yoast markup.

You can also copy paste the code along with the script on https://validator.schema.org/ , to validate your schema.

Leave a Reply