LocalBusiness Structured Data for Each Location Page
Adds LocalBusiness JSON-LD (address, phone, opening hours and map coordinates) to every branch or store page of a Locations post type.
Opens WPIDE on
Code
// Schema type for each location.
$wpide_location_type = 'LocalBusiness';
add_action( 'wp_head', function () use ( $wpide_location_type ) {
if ( ! is_singular( 'location' ) ) {
return;
}
$post = get_queried_object();
$get = function ( $key ) use ( $post ) {
return trim( (string) get_post_meta( $post->ID, '_location_' . $key, true ) );
};
$data = array(
'@context' => 'https://schema.org',
'@type' => $wpide_location_type,
'@id' => get_permalink( $post ) . '#business',
'name' => get_bloginfo( 'name' ) . ' – ' . wp_strip_all_tags( get_the_title( $post ) ),
'url' => get_permalink( $post ),
'image' => get_the_post_thumbnail_url( $post, 'full' ),
'telephone' => $get( 'phone' ),
'openingHours' => array_values( array_filter( array_map( 'trim', explode( "\n", $get( 'hours' ) ) ) ) ),
'address' => array_filter( array(
'@type' => 'PostalAddress',
'streetAddress' => $get( 'street' ),
'addressLocality' => $get( 'city' ),
'addressRegion' => $get( 'region' ),
'postalCode' => $get( 'postcode' ),
'addressCountry' => $get( 'country' ),
) ),
'parentOrganization' => array( '@type' => 'Organization', 'name' => get_bloginfo( 'name' ), 'url' => home_url( '/' ) ),
);
if ( is_numeric( $get( 'lat' ) ) && is_numeric( $get( 'lng' ) ) ) {
$data['geo'] = array( '@type' => 'GeoCoordinates', 'latitude' => (float) $get( 'lat' ), 'longitude' => (float) $get( 'lng' ) );
}
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 Location Details meta box fields. Change the type to Restaurant, Store or another LocalBusiness subtype.
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.