Question

I am using the WP REST API plugin in wordpress and want to loop through my json data using a for each loop, however when I var_dump the variable that the json data is stored in it gives me an error.

"Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in C:\wamp\www\public_html\wp-content\themes\raj\template-wiki.php on line 22"

<?php $json = lusso_posts(); ?>

<?php var_dump($json); ?>

<?php echo ($json->wp-json->posts[1]->ID); ?>

I think the "wp-json" is conflicting with "->" this sign because when I remove the "-" from "wp-post", the error goes away but nothing shows.

CODE FROM LUSSO FUNCTION

` function lusso_posts() {

  // Do we have this information in our transients already?
  $transient = get_transient( 'lusso_posts' );

  // Yep!  Just return it and we're done.
  if( ! empty( $transient ) ) {

    // The function will return here every time after the first time it is   run, until the transient expires.
    return $transient;

  // Nope!  We gotta make a call.
  } else {

    // We got this url from the documentation for the remote API.
    $url = 'http://localhost/database2/wp-json/posts/';

    $body =  wp_remote_retrieve_body(wp_remote_get($url));

    $json = json_decode($body);


    // Call the API.
    //$out = wp_remote_get( $url, $args );

    // Save the API response so we don't have to call again until  tomorrow.
    set_transient( 'lusso_posts', $json, DAY_IN_SECONDS );

    // Return the list of subscribers.  The function will return here the first time it is run, and then once again, each time the transient expires.
    return $json;

  }

}`

Any help would be appreciated.

Thanks.

Was it helpful?

Solution

I managed to solve this and access the JSON data using a foreach loop:

$json = lusso_posts();
#var_dump( $json );
#die();

foreach( $json as $post ) { 
    $titles = $post->title;
    $images = $post->featured_image->guid;
    ?>
    <div class="lusso-posts">
        <div class="image-container"><img src="<?php echo $images; ?>" />    </div>
        <h4><?php echo $titles; ?></h4>
    </div>  
    <?php
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top