ItemList Structured Data on Archive Pages
Adds ItemList JSON-LD listing the posts shown on category, tag, post type and blog archive pages, using the posts already loaded so it adds no queries.
Opens WPIDE on
Code
add_action( 'wp_head', function () {
global $wp_query;
if ( ! ( is_home() || is_category() || is_tag() || is_tax() || is_post_type_archive() ) || empty( $wp_query->posts ) ) {
return;
}
$offset = ( max( 1, (int) get_query_var( 'paged' ) ) - 1 ) * (int) $wp_query->get( 'posts_per_page' );
$items = array();
foreach ( $wp_query->posts as $i => $post ) {
$items[] = array( '@type' => 'ListItem', 'position' => $offset + $i + 1, 'url' => get_permalink( $post ) );
}
echo '<script type="application/ld+json">' . wp_json_encode( array( '@context' => 'https://schema.org', '@type' => 'ItemList', 'itemListElement' => $items ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG ) . "</script>\n";
} );
Notes
Google uses ItemList for carousels of some content types, such as recipes and courses.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.