我正在wordpress中使用WP REST API插件,希望使用for-each循环遍历json数据,但是当我var\\u转储存储json数据的变量时,它会给我一个错误。
“分析错误:语法错误,在C:\\wamp\\www\\public\\u html\\wp content\\themes\\raj\\template-wiki.php的第22行出现意外的\'->\'(T\\u OBJECT\\u操作符)”
<?php $json = lusso_posts(); ?>
<?php var_dump($json); ?>
<?php echo ($json->wp-json->posts[1]->ID); ?>
我认为“wp-json”与“->”这个符号相冲突,因为当我从“wp-post”中删除“-”时,错误消失了,但什么也没有显示。
LUSSO函数的代码
`函数lusso\\u 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;
}
}`
任何帮助都将不胜感激。
谢谢
最合适的回答,由SO网友:Raj Chudasama 整理而成
我设法解决了这个问题,并使用foreach
回路:
$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
}