Aller au contenu principal
Version: 26.0.9.0

post

La variable globale post fournit un accès à la publication courante dans les templates de type single (article, page, CPT). C'est une instance de la façade Post, injectée automatiquement par Elementum via l'action WordPress wp.

Disponibilité

post n'est disponible que sur les templates singuliers (is_singular()). Elle n'est pas injectée sur les archives, la home, le 404, etc. Pour ces contextes, utilisez la variable page ou les variables fournies par {% wp_query %}.

Propriétés disponibles

PropriétéTypeDescription
idintID unique du post
titlestringTitre du post
contentstringContenu complet filtré par the_content (HTML)
slugstringSlug URL-friendly du post
datestringDate de publication au format WordPress (locale du site)
authorintID de l'auteur
excerptstringExtrait du post (vide si le type ne supporte pas excerpt)
featured_image_urlstringURL de l'image mise en avant
featured_imagestringBalise <img> de l'image mise en avant (taille full)
linkstringPermalien complet du post

Méthodes disponibles

get_terms(string $taxonomy)

Récupère les termes d'une taxonomie attachés au post courant. Retourne un tableau.

{% for cat in post.get_terms('category') %}
    <a href="{{ cat.link }}">{{ cat.name }}</a>
{% endfor %}

get_term(string $taxonomy)

Récupère le premier terme d'une taxonomie. Utile quand on n'affiche qu'une seule catégorie.

{% set cat = post.get_term('category') %}
{% if cat %}
    <span>{{ cat.name }}</span>
{% endif %}

get_field(string $field, mixed $default = false, ?int $postId = null)

Récupère la valeur d'un champ personnalisé (ACF ou champ natif).

{{ post.get_field('sous_titre') }}
{{ post.get_field('couleur', '#000000') }}

get_fields(?int $postId = null)

Récupère l'ensemble des champs personnalisés du post.

{% set fields = post.get_fields() %}

Exemple d'utilisation

{% extends '@theme/components/layouts/base.html.twig' %}

{% set title = post.title ~ ' | ' ~ site.name %}

{% block content %}
    <article>
        <h1>{{ post.title }}</h1>

        <p class="meta">
            Publié le {{ post.date }}
            {% for cat in post.get_terms('category') %}
                dans <a href="{{ cat.link }}">{{ cat.name }}</a>
            {% endfor %}
        </p>

        {% if post.featured_image_url %}
            <img src="{{ post.featured_image_url }}" alt="{{ post.title }}">
        {% endif %}

        <div class="content">
            {{ post.content }}
        </div>
    </article>
{% endblock %}

Ajouter des globals personnalisés

Vous pouvez injecter vos propres variables globales Twig depuis un contrôleur en hookant l'action elementum.twig.globals :

#[Action('elementum.twig.globals')]
public function globals(\Twig\Environment $twig): void
{
    $twig->addGlobal('session', $_SESSION);
}