Connections 接続

Updated :

段落ブロックをカスタムフィールドの値で置換する機能

WordPress 6.4では、まだコアに実装されていないGutenberg の機能です。

Gutenberg Pluginの実験中機能Connections(接続)を有効にする必要があります。

この機能を有効にすると、

カスタムフィールドメタキーという項目が表示されるようになります。

カスタムフィールドのキー名を入力すると、フロントエンドで、カスタムフィールドの値が表示されるようになります。

投稿で、よく使用する定型文や、ショートコードを使った簡単な計算結果を表示できるようです。

12/27 追記

この機能が実際に本領を発揮する場面としては、例えば非同期パターンを作成し、その一部の段落にカスタムフィールド名を入力しておくといった事で、投稿のカスタムフィールドの値でバインドできるという事になり、非同期パターンは部分同期するようになります。

非同期パターンは従来、単なるコピー機能でしたが、データバインドが可能になるとパターンの役割は大きく変化することになると思われます。

関連:同期パターンの部分同期

ショートコードで簡単な計算結果を表示する例

functions.php

カスタムフィールド year, month, dateを使って誕生日を入力しその値から年齢を計算する例

add_shortcode( 'age' , 'nobita_age' );
function nobita_age() {
global $post;
$now = date( "Ymd" );
$year = sprintf( '%04d', get_post_meta($post->ID,'year',true ) );
$month = sprintf( '%02d', get_post_meta($post->ID,'month',true ) );
$date = sprintf( '%02d', get_post_meta($post->ID,'date',true ) );

if( ! checkdate($month,$date,$year) ) {
return 'invalid date';
}

$birth = (int) $year . $month . $date;
return floor( ($now - $birth) / 10000 );

}

投稿の新規作成時にyear, month, date, ageフィールドを自動作成する例

functions.php

add_filter( 'default_content', 'my_default_content',10,2 );
function my_default_content( $content,$post ) {

add_post_meta($post->ID, 'year', ' ', true );
add_post_meta($post->ID, 'month', ' ', true );
add_post_meta($post->ID, 'date', ' ', true );
add_post_meta($post->ID, 'age', '[age]', true );

return $content;
}

実験コードのため、フィールドに値を入力しない場合は、invalid date と表示されます。