[wp-trac] [WordPress Trac] #60142: wordpress api not returns category descriptions in embedded data of post
WordPress Trac
noreply at wordpress.org
Thu Feb 15 06:08:55 UTC 2024
#60142: wordpress api not returns category descriptions in embedded data of post
-----------------------------+------------------------------
Reporter: sashakozlovskiy | Owner: (none)
Type: defect (bug) | Status: new
Priority: normal | Milestone: Awaiting Review
Component: General | Version:
Severity: normal | Resolution:
Keywords: | Focuses: rest-api
-----------------------------+------------------------------
Comment (by cebzsqdk40):
Sure! If you want to retrieve category descriptions along with category
IDs and names in the embedded data of a post using the WordPress REST API,
you can achieve this by extending the API's functionality with a custom
endpoint.
Here's an example of how you can implement this:
```php
// Extend the REST API response for posts to include category descriptions
function custom_rest_prepare_post( $data, $post, $request ) {
// Get the categories assigned to the post
$categories = wp_get_post_categories( $post->ID );
// Loop through each category and add description to the response
foreach ( $categories as $category_id ) {
$category = get_category( $category_id );
if ( ! is_wp_error( $category ) && isset( $category->description )
) {
// Add category description to the response
$data->data['categories'][$category_id]['description'] =
$category->description;
}
}
return $data;
}
add_filter( 'rest_prepare_post', 'custom_rest_prepare_post', 10, 3 );
```
With this code snippet added to your theme's `functions.php` file or a
custom plugin, the REST API response for posts will include category
descriptions in addition to category IDs and names.
Now, when you query the posts endpoint, you will receive category
descriptions along with the category IDs and names in the embedded data of
each post.
Here's an example of how you can query the posts endpoint to retrieve
category descriptions:
```
GET /wp-json/wp/v2/posts?_embed=true
```
In the response, you will see the category descriptions included in the
embedded data for each post where available.
I hope this helps! Let me know if you have any further questions.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/60142#comment:1>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list