我在wordpress网站的每个循环中都有一个for,用于输出用于结构化数据的内容。这在大多数情况下都可以正常工作,但是我看到正在输出实际数组以及其中的值。
所以我有以下内容:
"@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行上的数组到字符串的转换。这是指回声内爆行。不能完全确定那是否相关。
答案 0 :(得分:0)
数组的第一个键是:
$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'
);
因此,当您进行爆破时,将“ meta_query”键作为数组。 因此,在打印时会显示一个数组。如果要将数组转换为字符串,可以对其进行json_encode(在爆破之前):
'meta_query' => json_encode(array(
array(
'key' => 'event_end_date',
'compare' => '>=',
'value' => $today
)
)),
这取决于您要对该数组执行的操作。您必须自己解决嵌套问题。
编辑:(基于评论)
您在meta_query上有一个关联数组的数组。因此,它将打印一系列对象。如果要删除数组的两个级别,可以执行以下操作:
$args = array(
'numberposts' => -1,
'post_type' => 'events',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => json_encode(
array(
'key' => 'event_end_date',
'compare' => '>=',
'value' => $today
)
),
'meta_key' => 'event_start_date'
);
这将打印一个json对象。如果希望打印对象的对象,则必须将数组包含在关联数组中:
$args = array(
'numberposts' => -1,
'post_type' => 'events',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => json_encode(array(
'mykey' => array(
'key' => 'event_end_date',
'compare' => '>=',
'value' => $today
)
)),
'meta_key' => 'event_start_date'
);
但这全取决于您要对该数组执行的操作...