Last active
September 25, 2024 03:17
-
-
Save mennwebs/93f417ae413e81f6bed575470d191151 to your computer and use it in GitHub Desktop.
Add Blog related field to REST API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Add Blog related field to REST API /wp-json/wp/v2/blog | |
function blog_add_related_posts() | |
{ | |
register_rest_field('blog', 'related', [ | |
'get_callback' => function ($post) { | |
$categories = wp_get_post_categories($post['id']); | |
$related = get_posts([ | |
'post_type' => 'blog', | |
'category__in' => $categories, | |
'posts_per_page' => 3, | |
'post__not_in' => [$post['id']] | |
]); | |
return $related; | |
} | |
]); | |
} | |
add_action('rest_api_init', 'blog_add_related_posts'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment