Shortcode WordPressDEV
Mostra il menu Menu Facile in una pagina WordPress con uno shortcode e la cache.
Obiettivo: una pagina WordPress che mostra il menu del ristorante leggendolo dall'API Menu Facile, con una cache sul server per fare poche chiamate.
Caso d'uso
Il cliente ha già un sito WordPress (qualsiasi tema). Vuole una pagina "Il nostro menu" che mostri il menu aggiornato, senza copiare i piatti in WordPress: quando cambia un piatto sul pannello Menu Facile, il sito lo mostra alla scadenza della cache (5 minuti di default).
Codice
Aggiungi al functions.php del tema figlio (o meglio in un piccolo plugin):
<?php
/**
* Menu Facile — shortcode per WordPress.
* Uso: [menufacile base="https://<ristorante>.menufacile.it" lingua="it"]
*/
const MF_LINGUE = ['it', 'en', 'de', 'fr', 'es'];
function mf_api_get($url, $cache_key, $minutes) {
$data = get_transient($cache_key);
if (false !== $data) {
return $data;
}
$resp = wp_remote_get($url, ['timeout' => 5]);
if (is_wp_error($resp) || 200 !== wp_remote_retrieve_response_code($resp)) {
return null; // 404, 429, 503...: niente cache, si riprova alla prossima visita
}
$body = json_decode(wp_remote_retrieve_body($resp), true);
if (empty($body['success'])) {
return null;
}
set_transient($cache_key, $body['data'], max(1, $minutes) * MINUTE_IN_SECONDS);
return $body['data'];
}
function menufacile_render_menu($atts) {
$atts = shortcode_atts([
'base' => '', // es. https://ducatarocco.menufacile.it
'lingua' => 'it',
'cache_minutes' => 5,
], $atts, 'menufacile');
$base = untrailingslashit(esc_url_raw($atts['base']));
if ($base === '') {
return '<!-- Menu Facile: manca l\'attributo base -->';
}
// Una lingua sconosciuta nel percorso dà 404: meglio ricadere sull'italiano.
$lingua = in_array($atts['lingua'], MF_LINGUE, true) ? $atts['lingua'] : 'it';
$minutes = absint($atts['cache_minutes']);
$key = 'mf_' . md5($base . $lingua);
$menu = mf_api_get("{$base}/api/v1/menu/{$lingua}", "{$key}_menu", $minutes);
if (!$menu) {
return '<p class="mf-error">Menu temporaneamente non disponibile.</p>';
}
// Etichette leggibili degli allergeni, nella stessa lingua.
$allergeni = [];
foreach (mf_api_get("{$base}/api/v1/allergens?locale={$lingua}", "{$key}_allergeni", 24 * 60) ?? [] as $a) {
$allergeni[$a['key']] = $a['name'];
}
return menufacile_format_html($menu, $allergeni);
}
/**
* Gruppi da mostrare per una sezione. Con le sottocategorie lo stesso piatto
* è sia in $section['items'] sia in $section['types'][]['items']: qui ogni
* piatto esce una volta sola.
*/
function menufacile_groups($section) {
if (empty($section['show_subcategories']) || empty($section['types'])) {
return [['title' => null, 'items' => $section['items']]];
}
$groups = [];
foreach ($section['types'] as $type) {
$groups[] = [
'title' => !empty($type['is_visible']) ? $type['name'] : null,
'items' => $type['items'],
];
}
$loose = array_filter($section['items'], fn ($item) => $item['type_id'] === null);
if ($loose) {
$groups[] = ['title' => null, 'items' => $loose];
}
return $groups;
}
function menufacile_format_html($data, $allergeni) {
$html = '<div class="mf-menu">';
foreach ($data['sections'] as $section) {
$html .= '<section class="mf-section mf-section--' . esc_attr($section['menu_type']) . '">';
$html .= '<h2>' . esc_html($section['name']) . '</h2>';
if (!empty($section['notes'])) {
// notes è HTML scritto dal ristoratore: passa dal filtro di WordPress.
$html .= '<div class="mf-section-notes">' . wp_kses_post($section['notes']) . '</div>';
}
foreach (menufacile_groups($section) as $group) {
if ($group['title']) {
$html .= '<h3 class="mf-type">' . esc_html($group['title']) . '</h3>';
}
$html .= '<ul class="mf-items">';
foreach ($group['items'] as $item) {
$html .= '<li class="mf-item"><div class="mf-item-header">';
$html .= '<strong class="mf-item-name">' . esc_html($item['name']) . '</strong>';
$html .= '<span class="mf-item-price">€ ' . esc_html(number_format((float) $item['price'], 2, ',', '.')) . '</span>';
$html .= '</div>';
if ($item['description'] !== '') {
$html .= '<p class="mf-item-description">' . esc_html($item['description']) . '</p>';
}
if (!empty($item['allergens'])) {
$nomi = array_map(fn ($k) => $allergeni[$k] ?? $k, $item['allergens']);
$html .= '<p class="mf-item-allergens">Allergeni: ' . esc_html(implode(', ', $nomi)) . '</p>';
}
$html .= '</li>';
}
$html .= '</ul>';
}
$html .= '</section>';
}
if (!empty($data['settings']['allergen_info'])) {
$html .= '<div class="mf-allergen-info">' . wp_kses_post($data['settings']['allergen_info']) . '</div>';
}
return $html . '</div>';
}
add_shortcode('menufacile', 'menufacile_render_menu');
/**
* Stile minimo: spostalo nel CSS del tema o modificalo a piacere.
*/
function menufacile_inline_styles() {
echo '<style>
.mf-menu { max-width: 800px; margin: 0 auto; }
.mf-section { margin-bottom: 2rem; }
.mf-items { list-style: none; padding: 0; }
.mf-item { padding: 0.75rem 0; border-bottom: 1px solid #eee; }
.mf-item-header { display: flex; justify-content: space-between; gap: 1rem; }
.mf-item-price { font-weight: 600; white-space: nowrap; }
.mf-item-allergens { font-size: 0.85em; color: #666; margin: 0.25rem 0 0; }
</style>';
}
add_action('wp_head', 'menufacile_inline_styles');
Uso nella pagina
Crea una pagina "Il nostro menu" e inserisci lo shortcode (nell'editor a blocchi usa il blocco "Shortcode"):
[menufacile base="https://ducatarocco.menufacile.it" lingua="it"]
Versione inglese:
[menufacile base="https://ducatarocco.menufacile.it" lingua="en"]
Se il ristorante ha un dominio proprio collegato a Menu Facile puoi usare quello come base.
Cache più lunga (10 minuti):
[menufacile base="https://ducatarocco.menufacile.it" lingua="it" cache_minutes="10"]
Considerazioni
Lingua
La lingua nel percorso (/menu/en) decide i testi. Se un piatto non è tradotto, arriva nella lingua principale del ristorante. Le lingue che il ristorante cura davvero sono in settings.supported_locales: mostra il menu solo in quelle.
Sottocategorie
Nelle sezioni con sottocategorie lo stesso piatto è sia in items sia in types[].items. La funzione menufacile_groups() lo mostra una volta sola, nello stesso ordine del menu Menu Facile. Dettagli in API Reference.
Cache
I transient di WordPress stanno nel database (o in Redis se hai una object cache). Con cache_minutes=5 il sito chiama l'API al massimo una volta ogni 5 minuti per lingua, qualunque sia il traffico. Le risposte di errore non vengono messe in cache. L'API non avvisa quando il menu cambia (niente webhook): la scadenza della cache è il modo per restare aggiornato.
Aggiornare subito
Per vedere subito una modifica senza aspettare la scadenza, cancella i transient. Da WP-CLI:
wp transient list --search='mf_*' --fields=name
wp transient delete <nome>
Multilingua (Polylang/WPML)
In ogni versione della pagina passa la lingua giusta:
[menufacile base="https://ducatarocco.menufacile.it" lingua="it"]
[menufacile base="https://ducatarocco.menufacile.it" lingua="en"]
Tempi
wp_remote_get con timeout=5: se l'API non risponde, la pagina non resta bloccata oltre 5 secondi e mostra "Menu temporaneamente non disponibile".
SEO
Il menu è nell'HTML generato dal server: i motori di ricerca lo leggono. Per aggiungere i dati strutturati vedi Schema.org JSON-LD.
Hai bisogno di aiuto?
Scrivi a supporto@studio121.it.