How to send an array of categories and posts in wordpress functions.php?

Tags: , ,



I make a request to my custom endpoint function in functions.php :

add_action( 'rest_api_init', function () {
    register_rest_route( 'wp/v2', '/homepage/', array(
        'methods' => 'GET',
        'callback' => 'custom',
    ) );
} );

And in return I get an array of posts of an author id :

function custom( $data ) {
    $posts = get_posts( array(
        'author' => $data['17'],
    ) );
    
    if ( empty( $posts ) ) {
        return null;
    }

    return $posts;
}

I want to return all posts and all categories but I get an error :

return [$posts , $categories ];

How can I get All posts and all categories in a single array inside custom function ?

Answer

Ok try this

function custom( $data ) {
     $posts = get_posts( array(
         'post_type' => 'post'
         'author' => $data['17'],
         'numberposts' => -1
     ) );
        
     $categories = get_categories();
    
     return [$posts, $categories];
 }


Source: stackoverflow