asd*_*asd 6 wordpress graphql wp-graphql
目前,我已经创建了自定义帖子类型,其中包含名为“国家”和“实践领域”的自定义分类法。如果是简单的帖子,我可以这样做:
但对于自定义分类法,我不能这样做。我的目标是查询包含分类“国家 - 爱沙尼亚”和“实践区域 - 所有”的所有人员。我目前可以做的是:
或者:
WPGraphQL 中是否有逻辑运算符,或者我现在设置错误?
如果有任何建议,我将不胜感激!
小智 2
WPGraphQL 本身不支持按分类法过滤自定义帖子类型的查询。
但是,您可以通过在functions.php文件中添加此代码(并调整字段以满足您的要求)来添加您自己的子句:
// First, we register the field in the "where" clause.
add_action('graphql_register_types', function () {
$customposttype_graphql_single_name = "Country"; // Replace this with your custom post type single name in PascalCase
// Registering the 'categorySlug' argument in the 'where' clause.
// Feel free to change the name 'categorySlug' to something that suits your requirements.
register_graphql_field('RootQueryTo' . $customposttype_graphql_single_name . 'ConnectionWhereArgs', 'categorySlug', [
'type' => [ 'list_of' => 'String' ], // To accept multiple strings
'description' => __('Filter by post objects that have the specific category slug', 'your_text_domain'),
]);
});
// Next, we add a filter to modify the query arguments.
add_filter('graphql_post_object_connection_query_args', function ($query_args, $source, $args, $context, $info) {
$categorySlug = $args['where']['categorySlug']; // Accessing the 'categorySlug' argument.
if (isset($categorySlug)) {
// If the 'categorySlug' argument is provided, we add it to the tax_query.
// For more details, refer to the WP_Query class documentation at https://developer.wordpress.org/reference/classes/wp_query/
$query_args['tax_query'] = [
[
'taxonomy' => 'your_taxonomy', // Replace 'your_taxonomy' with your actual taxonomy key
'field' => 'slug',
'terms' => $categorySlug
]
];
}
return $query_args;
}, 10, 5);
Run Code Online (Sandbox Code Playgroud)
应用这些更改后,您应该能够检索按分类法过滤的自定义帖子列表,如下所示:
query GetCountries {
countries(where: { categorySlug: ["united-states", "france"] }) {
nodes {
id
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1411 次 |
最近记录: |