Created
November 9, 2019 03:36
-
-
Save danielpowney/9b01101049a98d1bd6a36d2c7cb501d5 to your computer and use it in GitHub Desktop.
Adds schema.org JSON-LD for MRP post ratings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Adds JSON-LD ratings for schema.org item types | |
*/ | |
function mrp_jsonld_ratings() { | |
if ( is_page() || is_single() ) { | |
$post_id = get_queried_object_id(); | |
if ($post_id == null) { | |
return; | |
} | |
// in case you only want to add rich snippets on posts which have auto placement enabled... | |
if ( ! apply_filters( 'mrp_can_apply_auto_placement', true, 'the_title', null, $post_id ) ) { | |
return; | |
} | |
$post_type = get_post_type( $post_id ); | |
$rating_form_id = MRP_Utils::get_rating_form( $post_id ); | |
$rating_result = MRP_Multi_Rating_API::get_rating_result( array( | |
'post_id' => $post_id, | |
'rating_form_id' => $rating_form_id | |
) ); | |
if ($rating_result == null | |
|| ($rating_result !== null && $rating_result['count_entries'] === 0)) { | |
return; | |
} | |
$item_type_map = [ | |
"post" => 'Product', | |
"page" => 'Product' | |
]; | |
$item_type = $item_type_map[$post_type]; | |
$post_title = get_the_title( $post_id ); | |
$post_thumbnail_url = get_the_post_thumbnail_url( $post_id ); | |
$post_excerpt = get_the_excerpt( $post_id ); | |
?> | |
<script type="application/ld+json"> | |
{ | |
"@context": "https://schema.org/", | |
"@type": "<?php echo $item_type; ?>", | |
"name": "<?php echo $post_title; ?>", | |
<?php if ($post_thumbnail_url) { ?> | |
"image": [ | |
"<?php echo $post_thumbnail_url; ?>" | |
], | |
<?php } if ($post_excerpt) { ?> | |
"description": "<?php echo esc_html($post_excerpt); ?>", | |
<?php } ?> | |
"aggregateRating": { | |
"@type": "AggregateRating", | |
"ratingValue": "<?php echo $rating_result['adjusted_star_result']; ?>", | |
"reviewCount": "<?php echo $rating_result['count_entries']; ?>" | |
} | |
} | |
</script> | |
<?php | |
} | |
} | |
add_action( 'wp_head', 'mrp_jsonld_ratings' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment