我目前正在使用下面的代码在我的索引上列出粘性帖子。php。
但是,当没有粘性帖子时,它会加载最新的帖子(最多显示“设置>阅读>博客帖子”中指定的数量)。
我如何修改脚本,以便在并没有粘性帖子的情况下,它会暂时退出?
query_posts(array(\'post__in\'=>get_option(\'sticky_posts\')));
if (have_posts()) :
while (have_posts()) : the_post();
我目前正在使用下面的代码在我的索引上列出粘性帖子。php。
但是,当没有粘性帖子时,它会加载最新的帖子(最多显示“设置>阅读>博客帖子”中指定的数量)。
我如何修改脚本,以便在并没有粘性帖子的情况下,它会暂时退出?
query_posts(array(\'post__in\'=>get_option(\'sticky_posts\')));
if (have_posts()) :
while (have_posts()) : the_post();
那是因为get_option
如果没有粘性帖子,将返回空数组,查询将默认为所有内容。
$sticky = get_option(\'sticky_posts\');
if (!empty($sticky)) {
$args[\'post__in\'] = $sticky;
$qry = new WP_Query(array(\'post__in\' => $sticky));
if ($qry->have_posts()) :
while ($qry->have_posts()) : $qry->the_post();
echo $post->post_title;
endwhile;
endif;
}
请不要使用query_posts
.在查询数据库之前,询问是否存在粘性帖子:
$stickies = get_option(\'sticky_posts\');
if ( $stickies )
{
// fetch posts
}
请阅读When should you use WP_Query vs query_posts() vs get_posts()? :)首先,在我们开始讨论基本问题之前,有一个hardly ever 使用的理由query_posts
. 它应该被视为不推荐使用,但大多数情况下都是这样。
它不会重置,但会在已经执行的主查询之后覆盖该查询。
更确切地说,使用get_posts
函数或WP_Query
类别:
$args = array(
\'post__in\' => get_option( \'sticky_posts\' ),
\'post_status\' => \'publish\'
);
$stickies = new WP_Query( $args );
if ( $stickies->have_posts() ) {
while ( $stickies->have_posts() ) {
$stickies->the_post();
// do something
}
}
// reset the $post global to its previous state
wp_reset_postdata();
如果无论是否找到粘性帖子,都希望更改主查询以不返回任何内容(在主页上),请使用pre_get_posts
措施:function wpse_96219_nothing_on_home( $query ) {
if ( is_home() ) {
$query->set( \'posts_per_page\', 0 );
}
}
add_action( \'pre_get_posts\', \'wpse_96219_nothing_on_home\' );
此循环显示主题选项中指定的特定类别中超过4个帖子标题的一篇特色帖子。我想做的是显示4个标题中的所有4个帖子,在4个标题之上。这4个标题来自这段代码<a class=\"listtitle\" href=\"<?php the_permalink() ?>\" rel=\"bookmark\" title=\"<?php printf( esc_attr__( \'Permalink to %s\', \'wpnewspaper\' ), the_title_attribute( \