Schema Markup for Display Posts Shortcode

<?php

/**
 * Schema Markup for Display Posts Shortcode
 * @author Bill Erickson
 * @link https://www.billerickson.net/code/schema-markup-display-posts-shortcode
 *
 * @param string $open_markup
 * @param array $atts, shortcode attributes
 * @param object $loop
 * @return string
 */
function ea_dps_schema( $open_markup, $atts, $loop ) {
	if( !empty( $atts['disable_schema'] ) && true === filter_var( $atts['disable_schema'], FILTER_VALIDATE_BOOLEAN ) )
		return $open_markup;
	
	$json = ea_json_summary_markup( $loop );
	return $json . $open_markup;
}
add_filter( 'display_posts_shortcode_wrapper_open', 'ea_dps_schema', 40, 3 );

/**
 * JSON Summary Markup
 * @link https://developers.google.com/search/docs/guides/mark-up-listings#summary-page--multiple-full-details-pages
 *
 */
function ea_json_summary_markup( $loop = false ) {
	global $wp_query;
	$loop = empty( $loop ) ? $wp_query : $loop;

	if( ! $loop->have_posts() )
		return;

	$output = array();
	foreach( $loop->posts as $i => $post ) {
		$position = $i + 1;
		$output [] = '{
		      "@type":"ListItem",
		      "position":' . $position . ',
		      "url":"' . get_permalink( $post->ID ) . '"
		  }';
	}

	return '<script type="application/ld+json">
	{
	  "@context":"http://schema.org",
	  "@type":"ItemList",
	  "itemListElement":[' . join( ',', $output ) . ']
	}
	</script>';
}

Bill Erickson

Bill Erickson is the co-founder and lead developer at CultivateWP, a WordPress agency focusing on high performance sites for web publishers.

About Me
Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk