0
if ($_GET['api'] == 'json' && isset($_GET['id'])) {

        $post = get_post($_GET['id']);   // $post contains the post object   

        header("content-type: application/json");
        echo json_encode($post);
}
die();

This code works, but if I want to extend it will not work In the second case(below) , if i write
?second=case&id=204 to the url i get Unexpected but if I write ?first=case&id=204 I get the request

if (isset($_GET['api'])) {
    if ($_GET['first'] == 'case' && isset($_GET['id'])) {
         // $query is the WP_Query Object
        $post = get_post($_GET['id']);   // $post contains the post object   

        header("content-type: application/json");
        echo json_encode($post);
    }
    if ($_GET['second'] == 'case' && isset($_GET['id'])) {
         // $query is the WP_Query Object
        $post = get_post($_GET['id']);   // $post contains the post object   

        header("content-type: application/json");
        echo json_encode($post);
    }
    die();
}
0

Most likely it's simply because $_GET['first'] is not defined when you try with ?second=case&id=204.

Instead, try this CODE (assuming first & second can't appear at the same time):

if (isset($_GET['api'])) {
    if (isset($_GET['first']) && $_GET['first'] == 'case' && isset($_GET['id'])) {
         // $query is the WP_Query Object
        $post = get_post($_GET['id']);   // $post contains the post object   

        header("content-type: application/json");
        echo json_encode($post);
    }
    else if (isset($_GET['second']) && $_GET['second'] == 'case' && isset($_GET['id'])) {
        // $query is the WP_Query Object
        $post = get_post($_GET['id']);   // $post contains the post object   

        header("content-type: application/json");
        echo json_encode($post);
    }
    die();
}
  • But why the die has to be there? – john-thomas Feb 10 '17 at 17:48
  • If your CODE ends there, then die() doesn't need to be there. If your CODE still continues with any output at all, then die() is needed, since any output after echo json_encode($post) may break json. – Fayaz Feb 10 '17 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.