【发布时间】:2020-06-15 06:23:39
【问题描述】:
我在 wordpress 网站中有一个 for each 循环,用于输出用于结构化数据的内容。这大部分工作正常,但我看到正在输出的实际数组以及其中的值。
所以我有以下内容:
"@context" : "http://schema.org",
"@type": ["ItemList", "events"],
"name": "<?php the_title(); ?>",
"url": "<?php echo $current_url ?>",
"itemListElement": [
$args = array(
'numberposts' => -1,
'post_type' => 'events',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'event_end_date',
'compare' => '>=',
'value' => $today
)
),
'meta_key' => 'event_start_date'
);
$myposts = get_posts($args);
foreach ($myposts as $mypost) {
$args[] =
'{
"@type": "ListItem",
"item": {
"@type": "Event",
"name": "' . get_the_title($mypost->ID) . '",
"location": "' . get_field( 'event_address', $mypost->ID) . '",
"startDate": "' . get_field( 'event_start_date', $mypost->ID ) . '",
"endDate": "' . get_field( 'event_end_date', $mypost->ID ) . '",
"description": "' . get_the_excerpt($mypost->ID) . '"
}
}';
}
echo implode( ', ', $args );
这个输出:
"@context" : "http://schema.org",
"@type": ["ItemList", "events"],
"name": "Forthcoming Shows",
"url": "http://localhost/forthcoming-shows/",
"itemListElement": [
-1, events, publish, date, DESC, Array, event_start_date, { // this should be just the curly brace
"@type": "ListItem",
"item": {
"@type": "Event",
"name": "name here",
"location": "this is the address",
"startDate": "25/06/2020",
"endDate": "25/06/2020",
"description": "some description"
}
}, {
"@type": "Event",
"name": "Another event",
"location": "an address",
"startDate": "25/06/2020",
"endDate": "25/06/2020",
"description": "some description"
}
}]
为什么我会在结果上方打印数组? 我还收到一条错误消息“注意:第 214 行中的数组到字符串的转换。它指的是 echo implode 行。不完全确定这是否相关。
【问题讨论】:
-
永远不要手动制作你的 json 字符串。使用
json_encode()或遭受头痛和脱发。 -
构建你完整的多维数据结构,然后在你完成修改后对其进行一次json_encode。再简单不过了。你走在一条肮脏的道路上。 :)
-
谢谢@mickmackusa,我将不得不调查一下。希望它对这种结构化数据的问题有很大帮助。不过,我仍然很想知道这里发生了什么
标签: php arrays wordpress foreach