我有一个特色帖子滑块,它使用“特色”标签。我有一个关于这个的查询,它用这个标签抓取了最近的3篇文章,并在滑块中显示它们。下面,我列出了所有类别的10篇左右的最新帖子。我如何编写一个查询来排除带有“特色”标记的3篇最新帖子,因为它们已经在滑块中(不希望帖子重复),但当它们从滑块上掉下来时(即现在是第4篇最新的“特色”帖子等),它们会出现在帖子列表中?
编辑:这是我的代码-我已经编写了一个快捷码,这样我就可以将其放入任何我想要的页面/小部件/等中,但获取3篇最新“特色”帖子的查询如下:
posts_per_page=3&post_type=post&tag=featured
获取所有类别中最近10篇帖子的查询是:
posts_per_page=10&post_type=post
希望这有帮助:)
谢谢:)
编辑#2:使用了@Chip Bennet的答案,在我的短代码中,几乎可以正常工作,但它只排除了一个特色帖子(我认为是最近的),而不是滑块上的所有3个帖子。代码如下:
function loopShortcode($atts) {
$excludeFeaturedPosts = array(
\'tag\' => \'featured\',
\'posts_per_page\' => 3
);
$featured_posts = new WP_Query($excludeFeaturedPosts);
$featured_post_ids = array();
foreach ( $featured_posts as $featured_post ) {
$featured_post_ids[] = $featured_post->ID;
}
wp_reset_query();
// Defaults
extract(shortcode_atts(array(
"posts_per_page" => \'\', // query parameters are defined by the user when you add the shortcode into the page
"post_type" => \'\'
), $atts));
$query_args = array(
"posts_per_page" => $posts_per_page,
"post_type" => $post_type,
"post__not_in" => $featured_post_ids
);
$listedPosts = new WP_Query($query_args);
// rest of short code content, e.g loop, output etc
return $output;
wp_reset_query();
} // end shortcode function
SO网友:Chip Bennett
假设上下文是Site Front Page (例如,自定义首页模板文件或自定义页面模板),而不是博客帖子索引或其他存档索引页面,最好的方法是在创建滑块查询时获取帖子ID,然后明确地从自定义最新帖子查询中排除它们:
// Slider args
$slider_posts_args = array(
\'tag\' => \'featured\',
\'posts_per_page\' => 3
);
// Slider query
$slider_posts = new WP_Query( $slider_posts_args );
// Grab post IDs
$slider_post_ids = array();
foreach ( $slider_posts as $slider_post ) {
$slider_post_ids[] = $slider_post->ID;
}
// Recent posts args
$recent_posts_args = array(
\'posts_per_page\' => 10,
\'post__not_in\' => $slider_post_ids
);
// Recent posts query
$recent_posts = new WP_Query( $recent_posts_args );
如果这是
Blog Posts Index, 您需要在以下位置筛选主查询:
pre_get_posts
, 并排除添加到滑块的帖子:
function wpse121428_pre_get_posts( $query ) {
// Blog posts index main query
if ( is_home() && $query->is_main_query() ) {
// Slider args
$slider_posts_args = array(
\'tag\' => \'featured\',
\'posts_per_page\' => 3
);
// Slider query
$slider_posts = new WP_Query( $slider_posts_args );
// Grab post IDs
$slider_post_ids = array();
foreach ( $slider_posts as $slider_post ) {
$slider_post_ids[] = $slider_post->ID;
}
// Remove slider posts from main query
$query->set( \'post__not_in\', $slider_post_ids );
}
}
add_action( \'pre_get_posts\', \'wpse121428_pre_get_posts\' );