Search code examples
phpwordpressadvanced-custom-fieldswordpress-rest-api

Add post with custom field value to WP Rest API


I have created a custom field for blog posts in 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. 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.


Solution

  • Add this into the functions.php file:

    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();      
                },
        ));
    });