【发布时间】:2021-03-23 10:00:26
【问题描述】:
我正在尝试从 WordPress PHP 循环自动生成模式标记。我正在尝试从我的“hovedret”WordPress 帖子类别中的五个最新帖子创建我的标记。
我正在尝试生成的架构标记:
<script type="application/ld+json">
{
"@context":"https://schema.org",
"@type":"ItemList",
"itemListElement":[
{
"@type":"ListItem",
"position":1,
"url":"http://example.com/peanut-butter-cookies.html"
},
{
"@type":"ListItem",
"position":2,
"url":"http://example.com/triple-chocolate-chunk.html"
},
{
"@type":"ListItem",
"position":3,
"url":"http://example.com/snickerdoodles.html"
}
]
}
</script>
我的代码应该遍历“hovedret”类别中的最新五篇文章,因此我将获得位置 1、2、3、4 和 5。我正在使用 get_the_permalink 来填写 URL。
我正在使用 wp_head 挂钩来在我的网站中返回我的代码。出于某种原因,该代码破坏了我的网站。我不确定我是否以正确的方式构建了我的 while 循环,或者我的代码有什么问题?我试过 echo 而不是 return $string;
关于我缺少什么的任何线索??
//SCHEMA MARKUP
function tt_hook_schema_new()
{
if ( is_category() )
{
$post_per_page = 5;
$the_query = new WP_Query( array( 'category_name' => 'hovedret', 'posts_per_page' => $post_per_page ) );
if ( $the_query->have_posts() )
{
$string .= '<script type="application/ld+json">
{
"@context":"https://schema.org",
"@type":"ItemList",
"itemListElement":[';
$counter = 0;
while ( $the_query->have_posts() )
{
$counter = $counter + 1;
$string .= '{';
$string .= '"@type":"ListItem",';
$string .= '"position":' . $counter;
$string .= '"url":"' . get_the_permalink() . '"';
$string .= '}';
if($counter != $post_per_page)
{
$string .= ',';
}
}
$string .= ']
}
</script>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
}
}
add_action('wp_head', 'tt_hook_schema_new');
【问题讨论】:
标签: php wordpress loops while-loop categories