简体   繁体   中英

Adding post fields to post data in custom WordPress REST API endpoint

I have a custom field that I have added to every wordpress post. I created an api endpoint that queries posts where the custom field is a certain value. That works great, the code is:

function fp_acf() {
    $args = array(
      'meta_key'   => 'featured_post', 
      'meta_value' => 'yes'
    );
    $the_query = new WP_Query( $args );
    return $the_query;
}
add_action('rest_api_init', function() {
    register_rest_route('wp/v2', 'featured_posts', array(
        'methods' => array('GET', 'POST'),
        'callback'    => function() {
                return fp_acf();        
            },
    ));
});

The Problem:

The data that is returned from that endpoint doesn't contain all of the post data that is typically included in, say "/wp/v2/posts", specifically the slug or link.

Question:

I am wondering if it is possible to add the slug of the posts returned in this question query endpoint to the post data being returned?

If I understood the problem correctly and under the presumption that you are using the ACF plugin, going by the function name fp_acf , you will want to register a custom REST field that contains the value of your desired ACF field.

To get this done you have to do the following:

  1. First, make sure all of your posts that the WP_Query is going over have the ability to be shown in the REST api.
    Default posts and pages already show in the REST api but for any custom post types you will need to add 'show_in_rest' => true to their register_post_type argument array.
  2. Next, you want to actually register the custom REST field, you do this in your rest_api_init callback like so:
add_action('rest_api_init', function() {
    
    // ...

    register_rest_field( array( 'your_post_type' ), 'is_featured_post', array(
        'get_callback' => function() {
            return get_field('featured_post');
        },
        'schema' => array(
            'description' => 'Shows whether the post is featured',
            'type'        => 'string'
        ),
    ));
});

Obviously, you can change the return value of the get_callback function to whatever you need. You should be able to use all of the same functions, such as get_the_permalink , get_the_title etc. as you would when looping over posts in a template.

NB you say you need to get the slug of the posts, you should find that there already is a slug property that is returned by the REST api for posts and pages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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