我正在编写一个要在自定义类别模板页面上使用的自定义多循环。循环应将一个在 admin 中被选中为精选的帖子放在单独的div 中,并继续循环显示该类别中除精选之外的所有帖子。
与 codex 页面上提供的示例类似,除了我不想为特色帖子创建单独的类别。
我正在使用高级自定义字段插件来设置帖子作为特色的复选框。
我的代码有以下问题:if ($post->ID == $do_not_duplicate) continue;
阻止执行循环的其余部分。下面的代码只是提取最新的特色帖子。
这是我的函数:
function featured() {
$featured = new WP_Query(array(
'meta_query' => array(
array(
'key' => 'featured',
'value' => '"top"',
'compare' => 'LIKE'
)
),
'posts_per_page' => 1
));
while ( $featured->have_posts() ) : $featured -> the_post();
$do_not_duplicate = $post->ID; ?>
<div id="featured">
//featured post
</div><!-- end #featured -->
<?php
endwhile;
if(have_posts()) : while (have_posts()) : the_post();
if ($post->ID == $do_not_duplicate) continue;
?>
<div class="container">
// normal posts
</div><!-- .charities-container -->
<?php
endwhile;
endif;
}
您新鲜的眼睛会有很大帮助!
谢谢!
看起来您的$post
变量没有通过循环分配当前帖子信息。据我所知,您可以尝试以下任一方法:
1) 全球$post
$post
变量位于featured()
函数范围内。因此,当您运行循环时,它不会被识别为global $post
变量,这是WordPress通过循环填充帖子信息的变量。只需在函数作用域的开头将$post
声明为 global
变量,您应该能够收集帖子信息:
function featured() {
global $post;
// ... all your function code, $post->ID should work now
}
或 2)使用get_the_ID()
您可以将 $post->ID
替换为 WP 的本机函数get_the_ID()
。这与前面的解决方案大致相同,因为此函数将自动从全局$post
对象中检索 ID
属性。我认为这是最好的解决方案,因为只要填充$post
对象(在调用the_post()
之后),只要使用post函数(get_the_ID()
,get_the_title()
等)就不必担心范围。
所以你可以替换这一行:
$do_not_duplicate = $post->ID;
为
$do_not_duplicate = get_the_ID();
和
if ($post->ID == $do_not_duplicate) continue;
为
if (get_the_ID() == $do_not_duplicate) continue;
尝试这些解决方案中的任何一种,我敢打赌两者都应该适合您。实际上,您从codex页面中获取的示例工作正常,问题是您在本地function
中应用了它。这样,您的$post
变量就是局部(函数作用域)变量,而不是global
变量。