Skip to content
Advertisement

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

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 ?

Advertisement

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];
 }
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement