Meta Field Block

Por Phi Phan
(44 avaliações)
Baixar
  • Versão:
    1.3.2
  • Última atualização:
    há 8 dias
  • Instalações ativas:
    mais de 5 mil
  • Versão do WordPress:
    6.5 ou maior
  • Testado até o WordPress:
    6.7.1
  • Versão do PHP:
    7.4 ou maior
  • Tags:

Hospedagem WordPress com plugin Meta Field Block

Onde hospedar o plugin Meta Field Block?

Este plugin pode ser hospedado em qualquer hospedagem que possua WordPress configurado. Recomendamos fortemente utilizar uma hospedagem confiável, com servidores especializados para WordPress, como o serviço de hospedagem de sites da MCO2.

Hospedando o plugin Meta Field Block em um provedor confiável

A MCO2, além de instalar o WordPress na versão mais nova para seus clientes, disponibiliza o plugin WP SafePress, um sistema exclusivo que salvaguarda e melhora seu site simultaneamente.

Por que a Hospedagem WordPress funciona melhor na MCO2?

A Hospedagem WordPress funciona melhor pois a MCO2 possui servidores otimizados para WordPress. A instalação de WordPress é diferente de uma instalação trivial, pois habilita imediatamente recursos como otimização de imagens, proteção da página de login, bloqueio de atividades suspeitas diretamente no firewall, cache avançado e HTTPS ativado por padrão. São plugins que potencializam seu WordPress para a máxima segurança e o máximo desempenho.

This single-block plugin allows you to display a meta field or a custom field as a block on the front end. It supports custom fields for posts, terms, and users. It can be nested inside a parent block that has postId and postType context, such as Query Block, or used as a stand-alone block.

You can display any field whose value can be retrieved by the core API (get_post_meta, get_term_meta, get_user_meta) and is a string or can be converted to a string. To display the field value in the Block Editor, it has to be accessible via the REST API or have the field type set to dynamic.

You can also display custom fields created by the Advanced Custom Fields plugin explicitly. It supports all ACF field types whose values are strings or can be converted to strings. Some other complex fields such as Image, Link, Page Link, True False, Checkbox, Select, Radio, Button Group, Taxonomy, User, Post Object and Relationship field types are also supported in basic formats.

This plugin also provides developer-friendly hook APIs that allow you to easily customize the output of the block, display complex data type fields, or use the block as a placeholder to display any kind of content with object_id and object_type as context parameters.

An edge case where this block is really helpful is when you need to get the correct post_id in your shortcode when you use it in a Query Loop. In that case, you can set the field type as dynamic and input your shortcode in the field name. The block will display it correctly on both the front end and the editor. Alternatively, if you only want to see the preview of your shortcode in the editor, you can also use this block as a better version of the core/shortcode.

Links

What is the HTML output of a custom field?

The HTML output of a custom field on the front end depends on the context of the field. It uses one of these core API functions to get the field value: get_post_meta, get_term_meta, get_user_meta.

What is the HTML output of ACF fields?

  1. All basic field types that return strings or can cast to strings are supported – The HTML output is from the get_field function.

  2. Link type – The HTML output is:

    <a href={url} target={target} rel="noreferrer noopener">{title}</a>
    

    There is no rel attribute if the target is not _blank

  3. Image type – The HTML output is from the wp_get_attachment_image function. The image size is from the Preview Size setting.

  4. True / False type – The HML output is Yes if the value is true, and No if the value is false. Below is the code snippet to change these text values:

    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 );
    
  5. Checkbox / Select type – The HTML output is:

    <span class="value-item">{item_value}</span>, <span class="value-item">{item_value}</span>
    

    The item_value can be either value or label, depending on the return format of the field. Multiple selected values are separated by ,. Below is the code snippet to change the separator:

    add_filter( 'meta_field_block_acf_field_choice_item_separator', function ( $separator, $value, $field, $post_id ) {
      return ' | ';
    }, 10, 4 );
    
  6. Radio button / Button group type – The HTML output can be either value or label, depending on the return format of the field.

  7. Page link type, Post object type – The HTML output for a single-value field is:

    <a class="post-link" href={url} rel="bookmark">{title}</a>
    

    For a multiple-value field is:

    <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>
    
  8. Relationship type – The HTML output is:

    <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>
    
  9. Taxonomy type – The HTML output is:

    <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>
    
  10. User type – The HTML output for a single-value field is:

    <a class="user-link" href={author_url}>{display_name}</a>
    

    For a multiple-value field is:

    <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>
    
  11. For other complex field types, you can generate a custom HTML output by using the hook:

    apply_filters( 'meta_field_block_get_acf_field', $field_value, $post_id, $field, $raw_value, $object_type )
    

    Or by using the general hook:

    apply_filters( 'meta_field_block_get_block_content', $content, $attributes, $block, $object_id, $object_type )
    

Copy & paste snippets

When using the meta_field_block_get_block_content hook to customize block content, we recommend selecting dynamic as the field type. This way, both the front end and the editor will show the changes. If you are working with ACF Fields, we suggest using the meta_field_block_get_acf_field hook to modify the field content.

  1. How to change the HTML output of the block?
    Using the meta_field_block_get_block_content hook:

    add_filter( 'meta_field_block_get_block_content', function ( $block_content, $attributes, $block, $post_id, $object_type ) {
      $field_name = $attributes['fieldName'] ?? '';
    
      if ( 'your_unique_field_name' === $field_name ) {
        $block_content = 'new content';
      }
    
      return $block_content;
    }, 10, 5);
    

    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, $object_type ) {
      $field_name = $field['name'] ?? '';
    
      if ( 'your_unique_field_name' === $field_name ) {
        $block_content = 'new content';
      }
    
      return $block_content;
    }, 10, 5);
    

    This basic snippet is very powerful. You can use it to display any fields from any posts, terms, users or setting fields. Please see the details in the below use cases.

  2. How to wrap the block with a link to the post within the Query Loop?
    Using the meta_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'] ?? '';
    
      if ( 'your_unique_field_name' === $field_name && $block_content !== '' ) {
        $block_content = sprintf('<a href="#">%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'] ?? '';
    
      if ( 'your_unique_field_name' === $field_name && $block_content !== '' ) {
        $block_content = sprintf('<a href="#">%2$s</a>', get_permalink($post_id), $block_content);
      }
    
      return $block_content;
    }, 10, 4);
    

    This snippet only works with the block that has only HTML inline tags or an image.

  3. How to display an image URL field as an image tag?
    Using the meta_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'] ?? '';
    
      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'] ?? '';
    
      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);
    
  4. How to display multiple meta fields in a block?
    For example, we need to display the full name of a user from two meta fields first_name and last_name.

    add_filter( 'meta_field_block_get_block_content', function ( $block_content, $attributes, $block, $post_id ) {
      $field_name = $attributes['fieldName'] ?? '';
    
      if ( 'full_name' === $field_name ) {
        $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 );
    
        $block_content = trim("$first_name $last_name");
      }
    
      return $block_content;
    }, 10, 4);
    

    Choose the field type as dynamic and input the field name as full_name.

  5. How to display a setting field?
    For example, we need to display a setting field named footer_credit on the footer template part of the site.

    add_filter( 'meta_field_block_get_block_content', function ( $block_content, $attributes, $block, $post_id ) {
      $field_name = $attributes['fieldName'] ?? '';
    
      // Replace `footer_credit` with your unique name.
      if ( 'footer_credit' === $field_name ) {
        $block_content = get_option( 'footer_credit', '' );
    
        // If the field is an ACF Field. The code will be:
        // $block_content = get_field( 'footer_credit', 'option' );
      }
    
      return $block_content;
    }, 10, 4);
    
  6. How to use MFB as a placeholder to display any kind of content?

SAVE YOUR TIME WITH MFB PRO

To display simple data type fields for posts, terms, and users, you only need the free version of MFB. MFB Pro can save you 90% of development time when working with ACF complex fields. It achieves this by transforming your ACF complex field types into container blocks, which work similarly to core container blocks. This eliminates the need for creating ACF custom blocks or writing custom code for displaying ACF complex fields.
Below is a video tutorial on how to use MFB Pro to build a post template without coding

The main features of MFB PRO are:

If this plugin is useful for you, please do a quick review and rate it on WordPress.org to help us spread the word. I would very much appreciate it.

Please check out my other plugins if you’re interested:

  • Content Blocks Builder – This plugin turns the Block Editor into a powerful page builder by allowing you to create blocks, variations, and patterns directly in the Block Editor without needing a code editor.
  • SVG Block – A block to display SVG images as blocks. Useful for images, icons, dividers, and buttons. It allows you to upload SVG images and load them into the icon library.
  • Icon separator – A tiny block just like the core/separator block but with the ability to add an icon.
  • Breadcrumb Block – A simple breadcrumb trail block that supports JSON-LD structured data and is compatible with WooCommerce.
  • Block Enhancements – Adds practical features to blocks like icons, box shadows, transforms, etc.
  • Counting Number Block – A block to display numbers with a counting effect
  • Better YouTube Embed Block – A block to solve the performance issue with embedded YouTube videos. It can also embed multiple videos and playlists.

The plugin is developed using @wordpress/create-block.

Capturas de tela

<p>Meta field settings</p>

Meta field settings

<p>Prefix and suffix settings</p>

Prefix and suffix settings

<p>Prefix and suffix style</p>

Prefix and suffix style

<p>Enable <code>Show in REST API</code> ACF setting</p>

Enable Show in REST API ACF setting

Plugins semelhantes

Editor clássico
(1.196 avaliações)

Ativar o editor "clássico" anterior e o estilo antigo da tela Editar Post com TinyMCE, Meta Boxes, etc. Suporta todos os plugins que estendem esta tela.

Widgets Clássicos
(253 avaliações)

Ativa a tela clássica de configuração de widgets em Aparência > Widgets e em Personalizar. Desativa o editor de blocos ao gerenciar widgets.

Secure Custom Fields
(1.361 avaliações)

Secure Custom Fields is a free fork of the Advanced Custom Fields plugin created originally for security updates, but now includes functionality impro …

Advanced Editor Tools
(339 avaliações)

Amplia e aprimora o editor de blocos (Gutenberg) e o editor clássico (TinyMCE).

Starter Templates — Elementor, WordPress & Beaver Builder Templates
(4.942 avaliações)

The growing library of 300+ ready-to-use templates that work with all WordPress themes including Astra, Hello, OceanWP, GeneratePress and more

Spectra – WordPress Gutenberg Blocks
(1.619 avaliações)

Power-up Gutenberg with advanced blocks for faster website creation. Build your WordPress website effortlessly using powerful building blocks!

Do mesmo author (Phi Phan)

SVG Block
(12 avaliações)

Display an SVG image as a block, which can be used for displaying images, icons, dividers, buttons

Content Blocks Builder – Create block, variation, repeater block with carousel, grid, accordion, popup, off-canvas layout
(12 avaliações)

Create your WordPress site easier and faster directly in the Gutenberg Block Editor without coding using core blocks and block themes.