Use this code when using local schemas:
// Add rating to LocalBusiness Schema
add_filter( 'rank_math/snippet/rich_snippet_localbusiness_entity', function( $entity ) {
// If you use custom fields, grab the dynamic values here
// Example: $rating = get_post_meta(get_the_ID(), 'business_rating', true);
$entity['aggregateRating'] = [
'@type' => 'AggregateRating',
'ratingValue' => '4.8', // Replace with dynamic variable if needed
'reviewCount' => '150', // Replace with dynamic variable if needed
'bestRating' => '5',
'worstRating' => '1',
];
return $entity;
});
Use this code when using global LocalBusiness Schema:
add_filter( 'rank_math/json_ld', function( $data, $jsonld ) {
// Check if Rank Math's LocalBusiness schema is present in the output array
if ( ! empty( $data['LocalBusiness'] ) ) {
// Inject the aggregateRating array directly into it
$data['LocalBusiness']['aggregateRating'] = [
'@type' => 'AggregateRating',
'ratingValue' => '4.9', // Replace with your dynamic value or ACF field
'reviewCount' => '142', // Replace with your dynamic value or ACF field
'bestRating' => '5',
'worstRating' => '1',
];
}
return $data;
}, 99, 2 ); // Priority 99 ensures this runs after Rank Math finishes compiling data
You can use both at the same time.
Rank Math sometimes groups Organization and LocalBusiness into 1 array so this might work instead:
add_filter( 'rank_math/json_ld', function( $data, $jsonld ) {
// Check if the schema graph exists and is an array
if ( ! empty( $data['@graph'] ) && is_array( $data['@graph'] ) ) {
// Loop through each schema object in the graph
foreach ( $data['@graph'] as $key => $schema_item ) {
// Check if the item contains the @type property
if ( ! empty( $schema_item['@type'] ) ) {
// Get the type(s) as an array to handle the ["LocalBusiness", "Organization"] setup
$types = (array) $schema_item['@type'];
// If it is our local business block, inject the rating properties
if ( in_array( 'LocalBusiness', $types ) ) {
$data['@graph'][$key]['aggregateRating'] = [
'@type' => 'AggregateRating',
'ratingValue' => '4.9', // Replace with your dynamic value or ACF field
'reviewCount' => '142', // Replace with your dynamic value or ACF field
'bestRating' => '5',
'worstRating' => '1',
];
break; // Stop looping once found and updated
}
}
}
}
return $data;
}, 99, 2 );