2026年10月22日
2026年10月22日
Advanced Custom FieldsのRelationship(関連)フィールド
はじめに
Advanced Custom Fields(以下、ACF)は、WordPressサイトのカスタマイズや機能拡張を効率的に行うための強力なプラグインです。その中でも、Relationshipフィールドは複数の投稿またはページを関連付けるために使用される重要な要素です。この記事では、Relationshipフィールドを使用する際の基本的な設定方法から応用までを詳しく説明します。
症状・背景
ACFのRelationshipフィールドが必要になる主な場面:
- カテゴリやタグに基づいて複数の投稿を関連付ける場合
- 同じ種類のページ群に共通の情報を追加したい場合
- 一覧形式で複数の記事を選択して表示する必要がある場合
手順・設定方法
ステップ1: Relationshipフィールドの作成
# フィールドグループを追加します
acf_add_local_field_group(array(
'key' => 'group_example',
'title' => 'Relationship Field Example',
'fields' => array(),
'location' => array(
array(
array(
'param' => 'post_type',
'operator' => '==',
'value' => 'your_post_type'
),
)
),
));
# フィールドを追加します
acf_add_local_field(array(
'key' => 'field_example_relationship',
'label' => 'Relationship Field',
'name' => 'relationship_field',
'type' => 'relationship',
'instructions' => '',
'required' => 0,
'conditional_logic' => 0,
'wrapper' => array(
'width' => '',
'class' => '',
'id' => ''
),
'post_object' => array(
'post_type' => array('your_post_type'),
'taxonomy' => '',
'field_groups' => array(0),
'min' => '',
'max' => '',
'returns' => 'ids',
'sortable' => 1,
'filterable' => 0,
),
));
ステップ2: 関連フィールドの使用
# フィールドを取得します
$related_posts = get_field('relationship_field');
# サムネイル画像を含む関連ポストのリストを表示します
foreach($related_posts as $post) {
setup_postdata( $post );
echo '<div class="related-post">';
the_title('<h3>', '</h3>');
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
echo '<p>' . get_the_excerpt() . '</p>';
echo '</div>';
}
wp_reset_postdata();
ステップ3: カスタムフィルタリングの実装
# 特定のカテゴリーのみを表示するカスタムフィルタリング
add_filter('acf/fields/relationship/query/name=relationship_field', 'filter_relationship_by_category');
function filter_relationship_by_category( $args ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'your-category-slug'
)
);
return $args;
}
ステップ4: トラブルシュートと監視
# フィールドのデータをデバッグします
$relationship_field = get_field('relationship_field');
var_dump($relationship_field);
注意事項
- サイトのパフォーマンスに影響を与えないように、大量の関連フィールドを使用しないでください。
- 関連する投稿が削除された場合、ACFはそれに対応してフィールドをクリアまたは更新します。
- フィルタリングやソート機能を使う際は、ユーザーインタラクションに影響を与えないように注意してください。
- セキュリティ上の問題を避けるため、適切なアクセス権限を設定する必要があります。
まとめ
1. 基本的なセットアップ: Relationshipフィールドを作成し、必要な投稿タイプやタクソノミーを指定します。
2. データの取得と表示: 関連フィールドからデータを取り出して、ウェブページに適切に表示します。
3. カスタムフィルタリング: 必要な場合、関連フィールドに対してカスタムのクエリフィルタを適用して、特定の条件に基づいてデータを絞り込みます。
4. トラブルシュートとデバッグ: データが予想通りに表示されない場合やパフォーマンス問題がある場合は、適切な方法でトラブルシュートを行います。
5. ベストプラクティスの遵守: 適切なセキュリティ設定と運用上の注意点を守ることで、サイト全体の性能と信頼性を向上させます。
関連記事: