Meta Field Block

説明

このプラグインは、開発者 / ユーザーがメタ フィールドをフロントエンドのブロックとして表示することができ、ACF フィールドもサポートできます。Query Block などの postIdpostType コンテキストを持つ親ブロック内にネストできるほか、単独のブロックとして使用することもできます。

ACF フィールドの HTML 出力とは何ですか ?

  1. すべての基本的なフィールドタイプ、文字列を返すか、文字列に変換できるものをサポート – HTML の出力は、get_field 関数により取得できます。

  2. リンクタイプ – HTML の出力:

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

    target_blank でない場合、rel 属性は存在しません

  3. 画像タイプ – HTML 出力は、wp_get_attachment_image 関数から取得されます。画像サイズはプレビュー サイズ設定から取得されます。

  4. True / False タイプ – 値が true の場合、HML 出力は Yes となり、値が false の場合は No となります。これらのテキスト値を変更するコードスニペットは以下です:

    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. チェックボックス / セレクトタイプ – HTML の出力:

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

    item_value は、フィールドの戻り形式に応じて、value または label になります。複数の選択値は、, で区切られます。区切り文字を変更するコードスニペットは以下です:

    add_filter( 'meta_field_block_acf_field_choice_item_separator', function ( $separator, $value, $field, $post_id ) {
      return ' | ';
    }, 10, 4 );
    
  6. ラジオボタン / ボタングループタイプ – HTML の出力は、フィールドの返り値フォーマットに依存しますので value または label です。

  7. ページリンクタイプ、投稿オブジェクトタイプ – 単一値フィールドの HTML 出力:

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

    複数の値を持つフィールドの場合は以下のようになります:

    <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. リレーションシップタイプの場合は以下のようになります:

    <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. タクソノミータイプ – HTML の出力:

    <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. ユーザータイプ – 単一値フィールドの HTML 出力:

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

    複数の値を持つフィールドの場合は以下のようになります:

    <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. 他の複雑なフィールドタイプに対して、カスタム HTML 出力を生成するには、以下のフックを使用できます:

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

    または、一般的なフックを使用してもかまいません:

    apply_filters( 'meta_field_block_get_block_content', $content, $attributes, $block, $post_id )
    

    フック meta_field_block_get_acf_field のメリットは、フロントエンドとエディターの両方で変更を確認できることです。

    これらのフックについて詳しくは、以下の「コピー & ペースト」の章で学びましょう。

コピー & ペーストのスニペット

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.

  1. ブロックの HTML 出力を変更するには ?
    meta_field_block_get_block_content フックを使用します:

    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);
    

    ACF フィールドに対してのみ、フック meta_field_block_get_acf_field を使用します:

    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);
    

    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. クエリループ内でブロックを投稿へのリンクでラップする方法は ?
    meta_field_block_get_block_content フックを使用します:

    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);
    

    ACF フィールドに対してのみ、フック meta_field_block_get_acf_field を使用します:

    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);
    

    このちらスニペットは、HTML インラインタグまたは画像のみを含むブロックでのみ機能します。

  3. 画像の URL フィールドを画像タグとして表示するには ?
    meta_field_block_get_block_content フックを使用します:

    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);
    

    ACF フィールドに対してのみ、フック meta_field_block_get_acf_field を使用します:

    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);
    
  4. 埋め込み URL (YouTube …) フィールドを埋め込み用の iframe として表示するには ?↵
    meta_field_block_get_block_content フックを使用:

    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);
    

    ACF フィールドに対してのみ、フック meta_field_block_get_acf_field を使用します:

    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);
    
  5. 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.

    // 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);
    

    Put the above snippet in your theme or plugin, then choose the field type as custom rest field and input the field name as full_name. Please make sure the rest field name is unique.

  6. How to display a term meta field?
    For example, we need to display the value of a custom field named cat_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 as custom rest field or meta and input the field name as unique_name_for_cat_attr. You can customize this snippet to display custom fields for a specific term on any page, or template.

  7. 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.

    // 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);
    

    ACF フィールドに対してのみ、フック meta_field_block_get_acf_field を使用します:

    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 or meta and input the field name as unique_name_for_footer_credit.

  8. ユーザーのカスタムフィールドを作者テンプレートで表示したり、ログインしているユーザーや他のユーザーのカスタムフィールドを表示するには ?

    // 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);
    

    Put the above snippet in your theme or plugin, drag the block into the template, then choose the field type as custom rest field or meta and input the field name as your_field_name.

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.

もし興味がありましたら、他のプラグインもチェックしてみてください:

  • Content Blocks Builder – ブロックエディターで、サイト用のブロック、パターン、またはバリエーションを簡単に作成するためのツール。
  • Block Enhancements – A plugin to add more useful features to blocks likes: icons, box-shadow, transform…
  • Icon separator – A tiny block just like the core/separator block but with the ability to add an icon to it.
  • SVG Block – A block to insert inline SVG images easily and safely. It also bundles with more than 3000 icons and some common non-rectangular dividers.
  • Counting Number Block – 数字のカウント効果を持つ数字を表示するためのブロックです。
  • Breadcrumb Block – JSON-LD 構造化データをサポートする、シンプルなパンくずリストブロックです。
  • Better Youtube Embed Block – サイトの動作を遅くさせることなく、YouTube の動画を埋め込むことができます。

このプラグインは @wordpress/create-block を使用して開発されています。

スクリーンショット

  • ブロックの設定

ブロック

このプラグインは1個のブロックを提供します。

  • Meta Field Block Display a meta field or a custom field as a block on the front end, supporting ACF fields.

インストール

  1. Upload the plugin files to the /wp-content/plugins/meta-field-block directory, or install the plugin through the WordPress plugins screen directly.
  2. WordPressの「プラグイン」画面よりプラグインを有効化してください

FAQ

このプラグインはどんな人に必要ですか ?

このプラグインは開発者向けに作成されました、もちろんエンドユーザーも使用できます。

メタ値の入力と保存をサポートしていますか ?

いいえ、提供しません。このブロックはメタフィールドをブロックとして表示するだけです。

すべての種類のメタフィールドをサポートしていますか ?

Only simple types such as string, integer, or number can be used directly. Other complex types such as object, array need to be converted to HTML markup strings.

すべての種類の ACF フィールドをサポートしていますか ?

It supports all basic field types that return strings or cast to strings. Some complex field types like image, link, page_link, post_object, relationship, taxonomy, and user are also supported in a basic format.

接頭辞と接尾辞は何のためにあるのでしょうか ?

The value for those settings should be plain text or some allowed HTML elements. Their values will be formatted with wp_kses( $prefix, wp_kses_allowed_html( "post" ) ). They’re helpful for some use cases like displaying the name of the meta field or a value with a prefix or suffix, e.g. $100, 100px, etc.

メタフィールドに対してスタイルは含まれていますか ?

このブロックは、メタフィールドの値に対して特定の CSS スタイルを提供しません。そのかわり設定から基本的なインラインスタイルを提供します。

他のメタフィールドフレームワークをサポートしていますか ?

はい、get_post_meta 関数を介してメタフィールドにアクセス可能で、戻り値が文字列または文字列にキャストできる場合に限り、サポートしております。ブロックエディタで値を表示するためには、REST API 経由でメタ フィールドにアクセスする必要があります。

表示されるマークアップが空白、またはメタフィールドの値と異なる場合はどうなりますか ?

There is a chance that your meta value contains some HTML tags or HTML attributes that are not allowed to display. To fix this, you should use the hook apply_filters( 'meta_field_block_kses_allowed_html', $allowed_html_tags ) to add your tags and attributes to the array of allowed tags. By default, the block allows all tags from the $allowedposttags value and basic attributes for iframe and SVG elements.

評価

2023年8月22日 2 replies
This plugin has helped me so much. Wordpress blocks don't seem to support getting the POST ID inside of a query block. This plugin solves that for me and allows me to use php to modify the output to my liking.
2023年7月25日 1 reply
Great job thanks! Its good to have metafields on product block!Now i need print attributes from product but dont know how.If you can explain will be great, also you can supply source code of block and then i can modify by myself.Thanks in advance!
32件のレビューをすべて表示

貢献者と開発者

Meta Field Block はオープンソースソフトウェアです。以下の人々がこのプラグインに貢献しています。

貢献者

“Meta Field Block” は3ロケールに翻訳されています。 翻訳者のみなさん、翻訳へのご協力ありがとうございます。

“Meta Field Block” をあなたの言語に翻訳しましょう。

開発に興味がありますか ?

コードを閲覧するか、SVN リポジトリをチェックするか、開発ログRSS で購読してみてください。

変更履歴

1.1.7

Release Date – 09 September 2023

  • FIX – The block does not show 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