MenuFacile

Schema.org JSON-LD per SEODEV

Genera dati strutturati Restaurant + Menu da inserire nella pagina del menu sul sito del cliente.

Obiettivo: trasformare la risposta di GET /api/v1/menu in un blocco JSON-LD schema.org/Restaurant con il menu annidato (hasMenu), da mettere nella pagina "Il nostro menu" del sito del ristorante.

Perché serve

Il vocabolario schema.org descrive ai motori di ricerca cosa c'è nella pagina: nome del ristorante, indirizzo, sezioni del menu, piatti e prezzi. È un segnale in più, non una garanzia: Google decide da solo se e come mostrare risultati arricchiti.

💡 Menu Facile inserisce già i dati strutturati nel menu ospitato su <ristorante>.menufacile.it. Questa ricetta serve quando il cliente ha il suo sito (es. ristorante.it) e vuole gli stessi dati sulla sua pagina del menu.

Regole per dati corretti

Codice (Next.js, App Router)

// app/menu/page.jsx
const API = 'https://<ristorante>.menufacile.it/api/v1/menu/it';

async function getMenu() {
  const res = await fetch(API, { next: { revalidate: 600 } }); // rilegge ogni 10 minuti
  const body = await res.json();
  if (!body.success) throw new Error(body.message);
  return body.data;
}

const plain = html => (html || '').replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim() || undefined;

function buildJsonLd({ settings, sections }) {
  return {
    '@context': 'https://schema.org',
    '@type': 'Restaurant',
    name: settings.name,
    address: settings.address
      ? { '@type': 'PostalAddress', streetAddress: settings.address }
      : undefined,
    telephone: settings.phone || undefined,
    url: 'https://www.ristorante.example', // ← il sito del cliente
    hasMenu: {
      '@type': 'Menu',
      name: `Menu di ${settings.name}`,
      hasMenuSection: sections.map(section => ({
        '@type': 'MenuSection',
        name: section.name,
        description: plain(section.notes),
        hasMenuItem: section.items.map(item => ({
          '@type': 'MenuItem',
          name: item.name,
          description: item.description || undefined,
          offers: {
            '@type': 'Offer',
            price: item.price.toFixed(2),
            priceCurrency: 'EUR',
          },
        })),
      })),
    },
  };
}

export default async function MenuPage() {
  const data = await getMenu();
  const jsonLd = buildJsonLd(data);

  return (
    <>
      <script
        type="application/ld+json"
        // "<" diventa <: un testo con "</script>" non può chiudere il tag.
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c') }}
      />
      <main>{/* il tuo HTML del menu qui */}</main>
    </>
  );
}

Codice (WordPress)

wp_head non riceve parametri: la funzione legge i dati da sola (con la stessa cache dello shortcode WordPress) e stampa il blocco solo sulla pagina del menu.

<?php
// functions.php del tema figlio, o un piccolo plugin.

const MF_JSONLD_BASE = 'https://<ristorante>.menufacile.it/api/v1'; // ← indirizzo del ristorante
const MF_JSONLD_PAGE = 'il-nostro-menu';                            // ← slug della pagina del menu

function mf_jsonld_menu_data($locale = 'it') {
    $cache_key = 'mf_jsonld_' . md5(MF_JSONLD_BASE . $locale);
    $data = get_transient($cache_key);
    if (false !== $data) {
        return $data;
    }

    $resp = wp_remote_get(MF_JSONLD_BASE . '/menu/' . rawurlencode($locale), ['timeout' => 5]);
    if (is_wp_error($resp) || 200 !== wp_remote_retrieve_response_code($resp)) {
        return null;
    }

    $body = json_decode(wp_remote_retrieve_body($resp), true);
    $data = $body['data'] ?? null;
    if ($data) {
        set_transient($cache_key, $data, 10 * MINUTE_IN_SECONDS);
    }

    return $data;
}

function mf_jsonld_plain($html) {
    $text = trim(preg_replace('/\s+/u', ' ', wp_strip_all_tags((string) $html)));
    return $text === '' ? null : $text;
}

function mf_jsonld_print() {
    if (!is_page(MF_JSONLD_PAGE)) {
        return;
    }

    $data = mf_jsonld_menu_data('it');
    if (!$data) {
        return; // niente dati, niente blocco: meglio di un blocco sbagliato
    }

    $sections = array_map(function ($section) {
        return array_filter([
            '@type' => 'MenuSection',
            'name' => $section['name'],
            'description' => mf_jsonld_plain($section['notes'] ?? ''),
            'hasMenuItem' => array_map(function ($item) {
                return array_filter([
                    '@type' => 'MenuItem',
                    'name' => $item['name'],
                    'description' => ($item['description'] ?? '') !== '' ? $item['description'] : null,
                    'offers' => [
                        '@type' => 'Offer',
                        'price' => number_format((float) $item['price'], 2, '.', ''),
                        'priceCurrency' => 'EUR',
                    ],
                ], fn ($v) => $v !== null);
            }, $section['items']),
        ], fn ($v) => $v !== null);
    }, $data['sections']);

    $settings = $data['settings'];
    $jsonld = array_filter([
        '@context' => 'https://schema.org',
        '@type' => 'Restaurant',
        'name' => $settings['name'],
        'address' => !empty($settings['address'])
            ? ['@type' => 'PostalAddress', 'streetAddress' => $settings['address']]
            : null,
        'telephone' => $settings['phone'] ?: null,
        'url' => home_url('/'),
        'hasMenu' => [
            '@type' => 'Menu',
            'name' => 'Menu di ' . $settings['name'],
            'hasMenuSection' => $sections,
        ],
    ], fn ($v) => $v !== null);

    // wp_json_encode con JSON_HEX_TAG: "<" e ">" escono come < e >.
    echo '<script type="application/ld+json">'
        . wp_json_encode($jsonld, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG)
        . "</script>\n";
}
add_action('wp_head', 'mf_jsonld_print');

Verifica

  1. Apri lo Schema Markup Validator
  2. Incolla l'URL della pagina del menu (pubblicata)
  3. Controlla che il blocco Restaurant sia letto senza errori
  4. Prova anche il Rich Results Test di Google

Cache

Il blocco è dentro l'HTML della pagina: si aggiorna quando la pagina viene rigenerata. Una cache della risposta API di 5-10 minuti basta; non serve una cache a parte per il JSON-LD.

Hai bisogno di aiuto?

Scrivi a supporto@studio121.it.