Description
L’extension permet d’afficher un champ méta sous forme de bloc sur l’interface publique et prend en charge les champs ACF. Il peut être imbriqué dans un bloc parent qui a un contexte postId
et postType
tel que le bloc Boucle de requête
ou utilisé de manière autonome.
Quel code HTML est généré pour les champs ACF ?
-
Tous les types de champs basiques qui renvoient des chaînes ou qui peuvent être convertis en chaînes sont pris en charge – La fonction
get_field
est utilisée pour générer le code HTML. -
Type Lien – Le code HTML généré est :
<a href={url} target={target} rel="noreferrer noopener">{title}</a>
Aucun attribut
rel
n’est ajouté si l’attributtarget
n’est pas égal à_blank
-
Type Image – Le code HTML généré provient de la fonction wp_get_attachment_image. La taille de l’image est définie par le réglage « Taille de l’aperçu ».
-
Type Vrai/Faux – Le code HTML généré est
Oui
si la valeur esttrue
, etNon
si la valeur estfalse
. Voir l’extrait de code ci-dessous pour modifier ces textes :add_filter( 'meta_field_block_acf_field_true_false_on_text', function ( $on_text, $field, $post_id, $value ) { return 'Yep'; }, 10, 4 ); add_filter( 'meta_field_block_acf_field_true_false_off_text', function ( $off_text, $field, $post_id, $value ) { return 'Noop'; }, 10, 4 );
-
Type Case à cocher/Liste déroulante – Le code HTML généré est :
<span class="value-item">{item_value}</span>, <span class="value-item">{item_value}</span>
item_value
peut être égal àvalue
oulabel
en fonction du format de présentation du champ. Plusieurs valeurs sélectionnées sont séparées par le caractère,
(virgule) et l’extrait de code ci-dessous permet de modifier ce séparateur :add_filter( 'meta_field_block_acf_field_choice_item_separator', function ( $separator, $value, $field, $post_id ) { return ' | '; }, 10, 4 );
-
Type Bouton radio/Groupe de boutons – Le code HTML généré est
value
oulabel
en fonction du format de présentation du champ. -
Type Lien vers la page, type Objet de la publication – Le code HTML généré pour un champ à valeur unique est :
<a class="post-link" href={url} rel="bookmark">{title}</a>
Pour un champ à valeur multiple :
<ul> <li><a class="post-link" href={url} rel="bookmark">{title}</a></li> <li><a class="post-link" href={url} rel="bookmark">{title}</a></li> </ul>
-
Type Relation – Le code HTML généré est :
<ul> <li><a class="post-link" href={url} rel="bookmark">{title}</a></li> <li><a class="post-link" href={url} rel="bookmark">{title}</a></li> </ul>
-
Type Taxonomie – Le code HTML généré est :
<ul> <li><a class="term-link" href={term_url}>{term_name}</a></li> <li><a class="term-link" href={term_url}>{term_name}</a></li> </ul>
-
Type Compte – Le code HTML généré pour un champ à valeur unique est :
<a class="user-link" href={author_url}>{display_name}</a>
Pour un champ à valeur multiple :
<ul> <li><a class="user-link" href={author_url}>{display_name}</a></li> <li><a class="user-link" href={author_url}>{display_name}</a></li> </ul>
-
Pour d’autres types de champ plus complexes, vous pouvez générer un code HTML personnalisé en utilisant le crochet :
apply_filters( 'meta_field_block_get_acf_field', $field_value, $post_id, $field, $raw_value )
Ou en utilisant le crochet général :
apply_filters( 'meta_field_block_get_block_content', $content, $attributes, $block, $post_id )
L’intérêt du crochet
meta_field_block_get_acf_field
est que vous pouvez voir les modifications aussi bien sur l’interface publique que sous l’éditeur.Pour plus d’informations sur ces crochets, voir la section « Copier & coller » ci-dessous.
Extraits à copier & coller
Most of the snippets using the hook meta_field_block_get_block_content
only affect the value on the front end, not in the editor.
If your fields are ACF Fields, we recommend using the hook meta_field_block_get_acf_field
to change the field content, because with that hook you can change the block content for both the front end and the editor. However, some snippets may not work on the editor because we cannot get the context in the REST API request.
-
How to change the HTML output of the block?
Using themeta_field_block_get_block_content
hook:add_filter( 'meta_field_block_get_block_content', function ( $block_content, $attributes, $block, $post_id ) { $field_name = $attributes['fieldName'] ?? ''; // Replace `your_field_name` with your unique name. if ( 'your_field_name' === $field_name ) { $block_content = 'new content'; } return $block_content; }, 10, 4);
Using the
meta_field_block_get_acf_field
hook for ACF Fields only:add_filter( 'meta_field_block_get_acf_field', function ( $block_content, $post_id, $field, $raw_value ) { $field_name = $field['name'] ?? ''; // Replace `your_field_name` with your unique name. if ( 'your_field_name' === $field_name ) { $block_content = 'new content'; } return $block_content; }, 10, 4);
Cet extrait basique est très puissant. Vous pouvez l’utiliser pour afficher n’importe quel champ provenant de publications, de termes, de comptes ou de réglages. Voir en détail les cas particuliers ci-dessous.
-
How to wrap the block with a link to the post within the Query Loop?
Using themeta_field_block_get_block_content
hook:add_filter( 'meta_field_block_get_block_content', function ( $block_content, $attributes, $block, $post_id ) { $field_name = $attributes['fieldName'] ?? ''; // Replace `your_field_name` with your unique name. if ( 'your_field_name' === $field_name && $block_content !== '' ) { $block_content = sprintf('<a href="%1$s">%2$s</a>', get_permalink($post_id), $block_content); } return $block_content; }, 10, 4);
Using the
meta_field_block_get_acf_field
hook for ACF Fields only:add_filter( 'meta_field_block_get_acf_field', function ( $block_content, $post_id, $field, $raw_value ) { $field_name = $field['name'] ?? ''; // Replace `your_field_name` with your unique name. if ( 'your_field_name' === $field_name && $block_content !== '' ) { $block_content = sprintf('<a href="%1$s">%2$s</a>', get_permalink($post_id), $block_content); } return $block_content; }, 10, 4);
Cet extrait fonctionne uniquement avec un bloc ayant des balises HTML « inline » ou une image.
-
How to display an image URL field as an image tag?
Using themeta_field_block_get_block_content
hook:add_filter( 'meta_field_block_get_block_content', function ( $block_content, $attributes, $block, $post_id ) { $field_name = $attributes['fieldName'] ?? ''; // Replace `your_image_url_field_name` with your unique name. if ( 'your_image_url_field_name' === $field_name && wp_http_validate_url($block_content) ) { $block_content = sprintf('<img src="%1$s" alt="your_image_url_field_name" />', esc_attr($block_content)); } return $block_content; }, 10, 4);
Using the
meta_field_block_get_acf_field
hook for ACF Fields only:add_filter( 'meta_field_block_get_acf_field', function ( $block_content, $post_id, $field, $raw_value ) { $field_name = $field['name'] ?? ''; // Replace `your_image_url_field_name` with your unique name. if ( 'your_image_url_field_name' === $field_name && wp_http_validate_url($block_content) ) { $block_content = sprintf('<img src="%1$s" alt="your_image_url_field_name" />', esc_attr($block_content)); } return $block_content; }, 10, 4);
-
How to display an embedded URL (YouTube …) field as an embedded iframe?
Using themeta_field_block_get_block_content
hook:add_filter( 'meta_field_block_get_block_content', function ( $block_content, $attributes, $block, $post_id ) { $field_name = $attributes['fieldName'] ?? ''; // Replace `your_embedded_url_field_name` with your unique name. if ( 'your_embedded_url_field_name' === $field_name && wp_http_validate_url($block_content) ) { $block_content = wp_oembed_get( $block_content, array( 'width' => 1024 ) ); } return $block_content; }, 10, 4);
Using the
meta_field_block_get_acf_field
hook for ACF Fields only:add_filter( 'meta_field_block_get_acf_field', function ( $block_content, $post_id, $field, $raw_value ) { $field_name = $field['name'] ?? ''; // Replace `your_embedded_url_field_name` with your unique name. if ( 'your_embedded_url_field_name' === $field_name && wp_http_validate_url($block_content) ) { $block_content = wp_oembed_get( $block_content, array( 'width' => 1024 ) ); } return $block_content; }, 10, 4);
-
Comment afficher plusieurs champs méta dans un même bloc ?
Par exemple, si nous avons besoin d’afficher le nom d’un utilisateur ou d’une utilisatrice à partir de deux champs métaprénom
etnom
.// Create a function to build the full name from two meta fields. function yourprefix_get_full_name( $post_id ) { $first_name = get_post_meta( $post_id, 'first_name', true ); $last_name = get_post_meta( $post_id, 'last_name', true ); // If the meta fields are ACF Fields. The code will be: // $first_name = get_field( 'first_name', $post_id ); // $last_name = get_field( 'last_name', $post_id ); return trim("$first_name $last_name"); } // Register a custom rest field for the full name. add_action( 'rest_api_init', function () { register_rest_field( 'post', // Can be an array of post types or a singular value like 'post', 'page', 'product' etc. 'full_name', array( 'get_callback' => function ( $post_array ) { return yourprefix_get_full_name( $post_array['id'] ); }, 'schema' => array( 'type' => 'string', ), ) ); } ); // Render the block on the front end. add_filter( 'meta_field_block_get_block_content', function ( $block_content, $attributes, $block, $post_id ) { $field_name = $attributes['fieldName'] ?? ''; if ( 'full_name' === $field_name ) { $block_content = yourprefix_get_full_name( $post_id ); } return $block_content; }, 10, 4);
Mettez l’extrait ci-dessus dans votre thème ou extension, puis choisissez le type de champ
champ personnalisé REST
et remplacezfull_name
par le nom du champ. Veuillez vous assurer que le nom du champ REST est unique. -
How to display a term meta field?
For example, we need to display the value of a custom field namedcat_attr
for the product_cat taxonomy.// Create a function to build the value for the field. function yourprefix_get_attr_value( $term_id ) { $cat_attr_value = get_term_meta( $term_id, 'cat_attr', true ); // If the meta field is an ACF Field. The code will be: // $cat_attr_value = get_field( 'cat_attr', 'term_' . $term_id ); return $cat_attr_value; } // Render the block on the front end. add_filter( 'meta_field_block_get_block_content', function ( $block_content, $attributes, $block, $post_id ) { $field_name = $attributes['fieldName'] ?? ''; // Replace `unique_name_for_cat_attr` with your unique name. if ( 'unique_name_for_cat_attr' === $field_name && is_tax( 'product_cat' ) ) { $term_id = get_queried_object_id(); $block_content = yourprefix_get_attr_value( $term_id ); } return $block_content; }, 10, 4);
Put the above snippet in your theme or plugin, drag the block into the
product_cat
taxonomy template, then choose the field type ascustom rest field
ormeta
and input the field name asunique_name_for_cat_attr
. You can customize this snippet to display custom fields for a specific term on any page, or template. -
How to display a setting field?
For example, we need to display a setting field namedfooter_credit
on the footer template part of the site.// Create a function to build the value for the field. function yourprefix_get_footer_credit_text() { $footer_credit_text = get_option( 'footer_credit', '' ); // If the field is an ACF Field. The code will be: // $footer_credit_text = get_field( 'footer_credit', 'option' ); return $footer_credit_text; } // Render the block on the front end. add_filter( 'meta_field_block_get_block_content', function ( $block_content, $attributes, $block, $post_id ) { $field_name = $attributes['fieldName'] ?? ''; // Replace `unique_name_for_footer_credit` with your unique name. if ( 'unique_name_for_footer_credit' === $field_name ) { $block_content = yourprefix_get_footer_credit_text(); } return $block_content; }, 10, 4);
Using the
meta_field_block_get_acf_field
hook for ACF Fields only:add_filter( 'meta_field_block_get_acf_field', function ( $block_content, $post_id, $field, $raw_value ) { $field_name = $field['name'] ?? ''; // Replace `unique_name_for_footer_credit` with your unique name. if ( 'unique_name_for_footer_credit' === $field_name ) { $block_content = yourprefix_get_footer_credit_text(); } return $block_content; }, 10, 4);
Put the above snippet in your theme or plugin, drag the block into the template, then choose the field type as
custom rest field
ormeta
and input the field name asunique_name_for_footer_credit
. -
Comment afficher les champs personnalisés pour les comptes sur le modèle d’auteur/autrice ou afficher les champs personnalisés pour l’internaute connecté ou tout autre utilisateur/utilisatrice ?
// Create a function to build the value for the field. function yourprefix_get_user_field( $user_id ) { $user_field_value = get_user_meta( $user_id, 'your_field_name', true ); // If the meta field is an ACF Field. The code will be: // $user_field_value = get_field( 'your_field_name', 'user_' . $user_id ); return $user_field_value; } // Render the block on the front end. add_filter( 'meta_field_block_get_block_content', function ( $block_content, $attributes, $block, $post_id ) { $field_name = $attributes['fieldName'] ?? ''; // Replace your_field_name with your unique name. if ( 'your_field_name' === $field_name && is_author() ) { $user_id = get_queried_object_id(); $block_content = yourprefix_get_user_field( $user_id ); } // If you want to display meta fields for logged-in users, then the code would be: // if ( 'your_field_name' === $field_name && is_user_logged_in() ) { // $user_id = get_current_user_id(); // $block_content = yourprefix_get_user_field( $user_id ); // } return $block_content; }, 10, 4);
Mettez l’extrait ci-dessus dans votre thème ou extension, faites glisser le bloc dans le modèle, puis choisissez le type de champ comme
custom rest field
oumeta
et saisissez le nom du champ commeyour_field_name
. -
How to use MFB as a placeholder to display any kind of content?
Si cette extension vous est utile, veuillez s’il vous plait laisser un avis et une note sur WordPress.org pour la faire connaître au plus grand nombre. Ce serait très apprécié.
Vous pouvez consulter mes autres extensions si cela vous intéresse :
- Content Blocks Builder – Un outil pour créer facilement des blocs, des compositions ou des variations pour votre site directement sur l’éditeur de blocs.
- Block Enhancements – Une extension pour ajouter aux blocs des fonctionnalités pratiques telles que : icône, ombre portée, transformation…
- Icon separator – Un tout petit bloc comme le bloc « Séparateur » mais avec la possibilité d’y ajouter une icône.
- SVG Block – Un bloc pour insérer des images SVG en ligne facilement et en toute sécurité. Il contient également plus de 3000 icônes et certains séparateurs non rectangulaires courants.
- Counting Number Block – Un bloc pour afficher un compteur animé.
- Breadcrumb Block – Un simple bloc Fil d’Ariane qui prend en charge les données structurées JSON-LD.
- Better Youtube Embed Block – Intégrez des vidéos Youtube sans ralentir votre site.
Cette extension est développée en utilisant @wordpress/create-block.
Blocs
Cette extension fournit 1 bloc.
- Meta Field Block Display a meta field or a custom field as a block on the front end, supporting ACF fields.
Installation
- Téléverser les fichiers de l’extension dans le répertoire
/wp-content/plugins/meta-field-block
ou installez directement l’extension via l’écran des extensions WordPress. - Activez l’extension depuis la page « Extensions » de WordPress
FAQ
-
Qui a besoin de cette extension ?
-
Cette extension a été conçue pour les développeurs et développeuses, mais tout le monde peut l’utiliser.
-
Prend-il en charge la saisie et l’enregistrement de la valeur méta ?
-
Non. Il affiche uniquement les champs méta sous forme de blocs.
-
Prend-il en charge tous les types de champs méta ?
-
Seuls les types simples tels que chaîne, entier ou nombre peuvent être utilisés directement. Les autres types complexes tels qu’objet ou tableau doivent être convertis en chaînes de balisage HTML.
-
Prend-il en charge tous les types de champs ACF ?
-
Il prend en charge tous les types de champs de base qui renvoient des chaînes ou qui sont convertis en chaînes. Certains types de champs complexes tels que les champs Image, Lien, Lien vers page, Objet publication, Relation, Taxonomie, et Compte sont également pris en charge de manière basique.
-
À quoi servent le préfixe et le suffixe ?
-
La valeur de ces réglages doit être du texte brut ou certaines balises HTML autorisées. Leurs valeurs seront formatées avec
wp_kses( $prefix, wp_kses_allowed_html( "post" ) )
. Ils sont utiles dans certains cas comme pour l’affichage du nom du champ méta ou l’affichage d’une valeur avec un préfixe ou un suffixe, par exemple 100 $, 100 px, etc. -
Inclut-il un style pour le champ méta ?
-
Le bloc ne fournit aucun style CSS pour la valeur du champ méta. Mais il fournit dans les réglages un style basique pour le positionnement du champ.
-
Prend-il en charge d’autres frameworks de champs méta ?
-
Yes, it does, as long as those meta fields can be accessed via the
get_post_meta
function and the return value is a string or can be cast to a string. To display the value in the block editor, the meta field has to be accessed via the REST API. -
Que se passe-t-il si le balisage affiché est vide ou différent de la valeur méta ?
-
Il est possible que la valeur de votre méta contienne des balises ou des attributs HTML qui ne sont pas autorisés à s’afficher. Pour corriger ce problème, vous devez utiliser le crochet
apply_filters( 'meta_field_block_kses_allowed_html', $allowed_html_tags )
pour ajouter vos balises et attributs au tableau des balises autorisées. Par défaut, le bloc autorise toutes les balises de la valeur$allowedposttags
et les attributs de base pour les élémentsiframe
etSVG
.
Avis
Contributeurs/contributrices & développeurs/développeuses
« Meta Field Block » est un logiciel libre. Les personnes suivantes ont contribué à cette extension.
Contributeurs“Meta Field Block” a été traduit dans 3 locales. Remerciez l’équipe de traduction pour ses contributions.
Traduisez « Meta Field Block » dans votre langue.
Le développement vous intéresse ?
Parcourir le code, consulter le SVN dépôt, ou s’inscrire au journal de développement par RSS.
Journal
1.1.7
Release Date – 09 September 2023
- FIX – The block does not show the number 0 if using it as the empty message
1.1.6
Release Date – 13 August 2023
- DEV – Refactor block.json, update to block API version 3 for better WP 6.3 compatibility
- FIX – Rename allowed HTML attributes for SVG
1.1.5
Release Date – 15 July 2023
- DEV – Add a custom hook
apply_filters( 'meta_field_block_kses_allowed_html', $allowed_html_tags )
for filtering allowed HTML tags in the value. - DEV – Allow displaying iframe, and SVG tag by default.
- DEV – Force displaying color (text, background, link) attributes for unsupported themes.
- DEV – Refactor code for React best practice.
- DOC – Update readme for the hook
meta_field_block_get_acf_field
1.1.4
Release Date – 20 May 2023
- DEV – Change the placeholder text for the block in the site editor.
- DEV – Add a setting to use the ACF field label as the prefix
1.1.3
Release Date – 31 Mar 2023
- DEV – Support choice fields: true/false, select, checkbox, radio, button group
- DEV – Add raw value to the
meta_field_block_get_acf_field
hook
1.1.2
Release Date – 28 Mar 2023
- DEV – Refactor both JS and PHP code
- DEV – Load ACF field value even if we could not load the field object
- DEV – Separate settings group for WP 6.2
1.1.1
Release Date – 14 Mar 2023
- DEV – Add a hideEmpty setting to hide the whole block if the value is empty
- DEV – Add an emptyMessage setting to show a custom text in case the value is empty
- FIX – The meta field did not show on the archive template
1.1.0
Release Date – 06 Mar 2023
- DEV – Refactor all the source code for more upcoming features
- DEV – Make sure the block works with all return formats for the image field, link field
- DEV – Get all custom rest fields to show on the suggested help
- DEV – Allow changing the tagName from the block toolbar
- DEV – Improve performance
- DEV – Add more core support features
- DEV – Add more meaningful messages for some use cases
- FIX – Allow displaying links without text
1.0.10
Release Date – 02 Feb 2023
- DEV – Support multiple values for ACF User type
1.0.9
Release Date – 15 Sep 2022
- FIX – Change the textdomain to the plugin slug
1.0.8
Release Date – 10 Sep 2022
- FIX – Wrong handle for wp_set_script_translations. Thanks to Loïc Antignac (@webaxones)
1.0.7
Release Date – 07 Sep 2022
- FIX – Add a null check for meta fields value before accessing it’s property
1.0.6
Release Date – 25 Jun 2022
- DEV – Add an option to show the block’s outline on the Editor
1.0.5
Release Date – 21 Jun 2022
- DEV – Display the placeholder text on the template context
1.0.4
Release Date – 02 May 2022
- DEV – Support displaying some field types for ACF such as image, link, page_link, post_object, relationship, taxonomy
1.0.3
Release Date – 30 April 2022
- DEV – Add supports for borders, and full typography options
1.0.2
Release Date – 28 April 2022
- DEV – Add the title to block registration in JS
- REFACTOR source code
1.0.1
Release Date – 23 March 2022
- FIX – The block does not work in the site editor.
1.0.0
Release Date – 22 February 2022