How to create REST Based JSON API(how to modify the code below)?

    if(isset($_GET['api']) ) {
            if ($_GET['api'] == 'json'){
                   $args = array(  
                       'post_type' = 'post'

                   );
                   $query = new WP_Query( $args ); // $query is the WP_Query Object
                   $posts = $query-get_posts();   // $posts contains the post objects


                   foreach( $posts as $post ) {    // Pluck the id and title attributes
                       $output[] = array( 
                        'id' = $post-ID, 
                        'title' = $post-post_title, 
                        'content' = $post -post_content,
                        'imageurl' = wp_get_attachment_url( get_post_thumbnail_id($post-ID) )
                        );
                   }
                   header("content-type: application/json");


                   echo json_encode( $output );
            }
           exit();
        }  
    }

This is what I get as a result:

[
      {
        "id": 95,
        "title": "See you next year!",
        "content": "Lorem ipsum",
        "imageurl": "http://localhost/....(random url)dsad.jpg"
      },
      {
        "id": 19,
        "title": "Early bird tickets",
        "content": "that is good",
        "imageurl": http://localhost/....(random url)dsada.jpg"
      }
    ]

How can I modify it so that I will only access the ID, or the Title, not all?

Topic web-services rest-api json api posts Wordpress

Category Web


try this:

if (isset($_GET['api'])) {
     if ($_GET['api'] == 'json' && isset($_GET['id'])) {
        $args = array(
            'p' => $_GET['id'],
             'post_type' => 'any'// ID of a page, post, or custom type
        );
        $query = new WP_Query($args); // $query is the WP_Query Object
        $post = $query->post;   // $post contains the post object   
        header("content-type: application/json");

        echo json_encode($post);
    }
     exit();
}

get post will retrieve a single post, it returns an array so it can go directly to json_encode, you will have to add to the URL "id=XX" where X is a number.

If you have the latest version of wordpress i recommend you to use the built-in api WP REST Api

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.