简体   繁体   English

将带有自定义字段值的帖子添加到 WP Rest API

[英]Add post with custom field value to WP Rest API

I have created a custom field for blog posts in WordPress.我在 WordPress 中为博客文章创建了一个自定义字段。 It's a simple radio button for either "yes" or "no".这是“是”或“否”的简单单选按钮。 I am wondering if there is a way to add an array field to the WP REST API that will contain all of those posts that have "yes" selected.我想知道是否有一种方法可以向 WP REST API 添加一个数组字段,该字段将包含所有选择“是”的帖子。 I can provide more info if necessary.如有必要,我可以提供更多信息。 I haven't been able to find resources that really address this question specifically, but would appreciate any input or resources someone might have.我一直无法找到真正解决这个问题的资源,但希望得到任何人的意见或资源。

Add this into the functions.php file:将此添加到functions.php文件中:

function endpoint_acf() {
    $args = array(
      'meta_key'   => 'custom-fied-name', 
      'meta_value' => 'custom-field-value'
    );
    $the_query = new WP_Query( $args );
    return $the_query;
}

add_action('rest_api_init', function() {
    register_rest_route('wp/v2', 'endpoint-name', array(
        'methods' => array('GET', 'POST'),
        'callback'    => function() {
                return endpoint_acf();      
            },
    ));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM