0

When i retrieve a post from rest api i have the following response :

{
    "id": 2598,
    "date": "2018-10-15T06:20:10",
    "modified": "2019-05-16T23:35:50",
    "slug": "lorem-ipsum-dolor-sit-amet-consectetur-adipisicing-elit",
    "status": "publish",
    "type": "post",
    "link": "http://www.mywebsite.org/2018/10/15/lorem-ipsum-dolor-sit-amet-consectetur-adipisicing-elit/",
    "title": {
        "rendered": "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
    },
    "content": {
        "rendered": "<p>Eaque ipsa quae ab illo inventore veritatis et quasi. Eaque ipsa quae ab illo inventore veritatis et quasi. Et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam.</p>\n<h2>Et Harum Qidem Rerum</h2>\n<p>Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam. Quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat. Animi, id est laborum et dolorum fuga. Duis aute irure dolor in reprehenderit in voluptate velit.</p>\n<ul>\n<li>Excepteur sint occaecat cupidatat non proident, sunt in culpa.</li>\n<li>Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam.</li>\n</ul>\n<h3>Quis Nostrum</h3>\n<p>Do eiusmod tempor incididunt ut labore et dolore magna aliqua. Totam rem aperiam. Esse cillum dolore eu fugiat nulla pariatur.</p>\n<h4>Ut Enim</h4>\n<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit. Accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo. Ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat. Et harum quidem rerum facilis est et expedita distinctio.</p>\n<ol>\n<li>Cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia.</li>\n<li>Accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo.</li>\n<li>Ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</li>\n</ol>\n<h5>Lorem Ipsum Dolor Sit Amet</h5>\n<p>Et harum quidem rerum facilis est et expedita distinctio. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae.</p>\n<h6>Quis Nostrum</h6>\n<p>Ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat. Ut enim ad minim veniam, quis nostrud exercitation ullamco. Ut enim ad minim veniam, quis nostrud exercitation ullamco. Nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat.</p>\n",
        "protected": false
    },
    "excerpt": {
        "rendered": "<p>Eaque ipsa quae ab illo inventore veritatis et quasi. Eaque ipsa quae ab illo inventore veritatis et quasi. Et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam. Et Harum Qidem Rerum Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis [&hellip;]</p>\n",
        "protected": false
    },
    "author": 1,
    "sticky": false,
    "template": "",
    "meta": [],
    "categories": [
        73
    ],
    "tags": [
        63,
        66,
        68
    ],
    "author_name": "Pracede",
    "featured_image_url": "http://www.mywebseite.org/wp-content/uploads/2018/10/placeholder.jpg"
}

Fields author_name and featured_image_url are custom. I would like to have categories and tags name instead of ids. In my functions.php i add the following code.

  1. Code to return tag names under attributes tag_names.

     function ag_filter_post_json($response, $post, $context) {
        $tags = wp_get_post_tags($post->ID);
        $response->data['tag_names'] = [];
        foreach ($tags as $tag) {
           $response->data['tag_names'][] = $tag->name;
       }
     return $response;
    }
    add_filter( 'rest_prepare_post', 'ag_filter_post_json', 10, 3 );```
    
  2. Code to return categories names under attributes categories_names :

        register_rest_field( 'post',
            'categories_names',
            array(
                'get_callback'    => 'enf_get_categories_names',
                'update_callback' => null,
                'schema'          => null,
            )
        );
    }
    add_action( 'rest_api_init', 'enf_register_categories_names_field' );
    function enf_get_categories_names( $object, $field_name, $request ) {
        $formatted_categories = array();
        $categories = get_the_category( $object['id'] );
        foreach ($categories as $category) {
            $formatted_categories[] = $category->name;
        }
        return $formatted_categories;
    }```
    

When i add these the above code on my functions.php, i don't have the tags names or the categories names. My output json remains the same. I always have category id and tags ids. Where am i wrong please ?

Thanks for your help.

1 Answer 1

1

When I copy/pasted your code I got an error message because enf_register_categories_names_field() wasn't defined.

When I cleaned up your code and wrapped the register_rest_field() in a function called "enf_register_categories_names_field" it worked as expected.

function ag_filter_post_json($response, $post, $context) {
    $tags = wp_get_post_tags($post->ID);
    $response->data['tag_names'] = [];
    foreach ($tags as $tag) {
        $response->data['tag_names'][] = $tag->name;
    }
    return $response;
}
add_filter( 'rest_prepare_post', 'ag_filter_post_json', 10, 3 );

function enf_register_categories_names_field(){
    register_rest_field( 'post',
        'categories_names',
        array(
            'get_callback'    => 'enf_get_categories_names',
            'update_callback' => null,
            'schema'          => null,
        )
    );  
}

add_action( 'rest_api_init', 'enf_register_categories_names_field' );

function enf_get_categories_names( $object, $field_name, $request ) {
    $formatted_categories = array();
    $categories = get_the_category( $object['id'] );
    foreach ($categories as $category) {
        $formatted_categories[] = $category->name;
    }
    return $formatted_categories;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.