Leon Gaban
Leon Gaban

Reputation: 39018

Can't GET JSON in wordpress php plugin

I'm testing an API I build locally with a local install of wordpress.

My API path is something like: http://local.web.tt.com:8615/api/product

With my Node server running it displays this in the browser when you go to that link (mongodb collections object]:

[
    {
        "_id":"54bd5fbb646174009a450001",
        "productname":"Product 1",
        "overview":"Overview Title",
        "benefits":
            [
                "List item 1",
                "List item 2",
                "List item 3"
            ]
    }
]

My PHP wordpress shortcode plugin

add_shortcode('product', function($atts, $content) {
    $service_url = 'http://local.web.tt.com:8615/api/product';
    $data = json_decode($service_url, true);

    return $data;
});

Basically nothing shows up on the page when I add [product] in a blog post. The shortcode does work if I return just a simple string.

I also just tried this:

add_shortcode('product', function($data) {
    $service_url = 'http://local.web.tt.com:8615/api/product';
    $get = file_get_contents($service_url);
    $data = json_decode($get, true);
    return $data;
});

However that just spits out Array into the spot where the shortcode goes:

enter image description here

What I'm trying to do is capture the strings in each of those keys of the JSON object, then nicely display them with HTML & CSS. ie: The Benefits array items will show up as bullet points.

Basically something like this:

$content .='
    <h2>$data.overview</h2>
    <ul>
       <li>$data.benefits[0]
       <li>$data.benefits[1]'

return $content;

Any idea what I'm missing? Thanks in advance!

Upvotes: 1

Views: 1519

Answers (1)

Karan
Karan

Reputation: 1187

{
"_id": "84b7e4c7946174009a1f0000",
"name": "Name of product",
"overview": "Long blah blah blah blah here...",
"benefits": [
    "List item 1",
    "List item 2",
    "List item 3",
    "List item 4"
]
}

fix your json to have quotes for keys

 $service_url = 'http://local.web.tt.com:8615/api/product'; 
 $get = file_get_contents($service_url);
 $data = json_decode($get, true);
 return $data;

Also, why are you returning the array ?

Upvotes: 1

Related Questions