概要
acf/fields/relationship/query フィルタは、Advanced Custom Fields (ACF) で使用される Relationship フィールドの投稿をクエリするために使用される $args をフィルターします。このフィルタを使用することで、特定の条件で投稿を絞り込み、表示される投稿をカスタマイズすることが可能です。以下のような機能を実装する際に役立ちます:
- 特定のカスタム投稿タイプのみを表示する。
- 特定のカテゴリやタグに基づいて投稿をフィルタリングする。
- デフォルトの順序を変更する。
- 特定のユーザーロールに基づいて投稿を制限する。
- ファイルやメタデータに基づいて条件を追加する。
- 投稿の表示非表示を管理するための論理チェックを加える。
構文
add_filter('acf/fields/relationship/query', 'my_relationship_query', 10, 3);
パラメータ
$args: WP_Query に渡される引数の配列。$field: フィールド情報の配列。$post_id: 現在のポストの ID。
戻り値
フィルタされた $args 配列。
バージョン
- ACF バージョン: 5.0+
- WordPress バージョン: 4.0+
この関数のアクションでの使用可能性
| アクション | 使用可能性 |
|---|---|
| mu_plugin_loaded | |
| registered_post_type | |
| plugins_loaded | |
| wp_roles_init | |
| setup_theme | |
| after_setup_theme | |
| set_current_user | |
| init | |
| register_sidebar | |
| wp_loaded | |
| send_headers | |
| parse_query | |
| pre_get_posts | |
| wp | |
| template_redirect | |
| get_header | |
| wp_head |
サンプルコード
サンプル 1: 特定の投稿タイプを表示する
このコードは、選択可能な投稿をカスタム投稿タイプ「book」のみでフィルタリングします。
add_filter('acf/fields/relationship/query', function($args, $field, $post_id) {
$args['post_type'] = 'book';
return $args;
});
引用元: https://www.advancedcustomfields.com/resources/relationship/
サンプル 2: 特定のカテゴリに基づいて投稿をフィルタリングする
このコードは、特定のカテゴリ「news」に属する投稿のみを表示します。
add_filter('acf/fields/relationship/query', function($args, $field, $post_id) {
$args['tax_query'] = [
[
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'news',
],
];
return $args;
});
引用元: https://www.advancedcustomfields.com/resources/relationship/
サンプル 3: 投稿の順序を変更する
このコードは、選択された投稿をタイトルのアルファベット順で並べ替えます。
add_filter('acf/fields/relationship/query', function($args, $field, $post_id) {
$args['orderby'] = 'title';
$args['order'] = 'ASC';
return $args;
});
引用元: https://www.advancedcustomfields.com/resources/relationship/
サンプル 4: ユーザーロールに基づいて投稿を表示する
このコードは、特定のユーザーロールを持つユーザーに対してのみ投稿を表示します。
add_filter('acf/fields/relationship/query', function($args, $field, $post_id) {
if (!current_user_can('editor')) {
$args['author'] = get_current_user_id();
}
return $args;
});
引用元: https://www.advancedcustomfields.com/resources/relationship/
サンプル 5: メタデータに基づいてフィルタリングする
このコードは、特定のメタフィールドを持つ投稿のみを選択します。
add_filter('acf/fields/relationship/query', function($args, $field, $post_id) {
$args['meta_query'] = [
[
'key' => 'featured',
'value' => '1',
],
];
return $args;
});
引用元: https://www.advancedcustomfields.com/resources/relationship/