Book Structured Data for a Books Post Type
Adds Book JSON-LD with author, ISBN, publisher, page count and publication date to single book pages.
Opens WPIDE on
Code
add_action( 'wp_head', function () {
if ( ! is_singular( 'book' ) ) {
return;
}
$post = get_queried_object();
$get = function ( $key ) use ( $post ) {
return trim( (string) get_post_meta( $post->ID, '_book_' . $key, true ) );
};
$data = array(
'@context' => 'https://schema.org',
'@type' => 'Book',
'name' => wp_strip_all_tags( get_the_title( $post ) ),
'description' => wp_strip_all_tags( get_the_excerpt( $post ) ),
'url' => get_permalink( $post ),
'image' => get_the_post_thumbnail_url( $post, 'full' ),
'isbn' => $get( 'isbn' ),
'numberOfPages' => absint( $get( 'pages' ) ),
'datePublished' => $get( 'published' ),
);
if ( $get( 'author_name' ) ) {
$data['author'] = array( '@type' => 'Person', 'name' => $get( 'author_name' ) );
}
if ( $get( 'publisher' ) ) {
$data['publisher'] = array( '@type' => 'Organization', 'name' => $get( 'publisher' ) );
}
echo '<script type="application/ld+json">' . wp_json_encode( array_filter( $data ), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG ) . "</script>\n";
} );
Notes
Reads the Book Details meta box fields.
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.