如何在WordPress中添加自定义字段查询功能?
请提供在WordPress中创建和管理自定义字段查询功能的方法。
-
玖比肆 评论若要在 WordPress 中添加自定义字段查询功能,可按照以下步骤进行操作:
1. 在主题中添加支持自定义字段的代码
在主题的 functions.php 文件中添加以下代码来支持自定义字段:
```
add_filter( 'rest_api_init', 'add_custom_fields' );
function add_custom_fields() {
register_rest_field( 'post',
'custom_fields',
array(
'get_callback' => 'get_post_custom_fields',
'update_callback' => null,
'schema' => null,
)
);
}function get_post_custom_fields( $object, $field_name, $request ) {
return get_post_meta( $object['id'] );
}
```这段代码将添加一个名为 custom_fields 的字段到 REST API 中的文章模型中。
2. 在文章中添加自定义字段
在 WordPress 后台编辑文章或页面时,可以通过“自定义字段”区域来添加自定义字段。输入一个自定义字段名和它对应的值即可。
例如,可以添加名为“author”的自定义字段,并设置其值为“John Smith”。
3. 通过 REST API 访问自定义字段数据
使用 REST API 可以方便地获取自定义字段数据。在浏览器中输入以下 URL 回车,即可获取到名为 my-post-title 的文章中的自定义字段数据:
```
https://example.com/wp-json/wp/v2/posts?slug=my-post-title&fields=custom_fields
```其中,example.com 应替换为你的网站域名,my-post-title 应替换为要获取自定义字段数据的文章的 slug 值。该 URL 中的 fields 参数告诉 WordPress 只返回 custom_fields 字段中的数据。
4. 创建自定义字段查询功能
使用以下代码,可以创建一个自定义函数来查询指定自定义字段的文章:
```
function get_posts_by_custom_field( $meta_key, $meta_value ) {
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => $meta_key,
'value' => $meta_value,
),
),
);$query = new WP_Query( $args );
return $query->get_posts();
}
```该函数需要两个参数:要查询的自定义字段名和要查询的自定义字段值。
在你的主题中插入该函数并调用它,即可获取到所有指定自定义字段的文章。
例如,可以使用以下代码将名称为 author 值为 John Smith 的文章列出来:
```
$posts = get_posts_by_custom_field( 'author', 'John Smith' );foreach ( $posts as $post ) {
echo '' . get_the_title( $post->ID ) . '
';
}
```这将列出所有作者为 John Smith 的文章的标题,以链接的形式显示在页面上。
以上就是在 WordPress 中添加自定义字段查询功能的方法。
2023年 5月 13日 上午12:54
