我想根据自定义字段有条件地将自定义帖子类型与我的帖子类型合并。如果该字段的值为1,那么我希望这些自定义帖子与主页上的帖子出现在同一个循环中。我可以将自定义post类型与默认posts post类型相结合,并且可以创建一个post id数组来排除post__not_in
, 但我不知道如何将其应用于主循环。这是我的索引代码。php模板如下:
if (is_home()) {
$exclude = array();
$newsQuery = new WP_Query (array(
"post_type" => "news",
"meta_key" => "post_to_blog",
"meta_value" => 1,
"meta_compare" => "!=",
"posts_per_page" => "-1",
));
while ($newsQuery->have_posts()) {
$newsQuery->the_post();
array_push($exclude, get_the_ID());
}
wp_reset_query();
}
if (have_posts()) {
while (have_posts()) {
the_post();
get_template_part("content", get_post_format());
}
}
if ($wp_query->max_num_pages > 1) {
echo "<div class=\\"pagination\\">";
kriesi_pagination();
echo "</div>";
}
下面是我在函数的主查询中显示自定义帖子类型的步骤。php:
function custom_home_loop($query) {
if ($query->is_main_query() && is_home()) {
$query->set("post_type", array("post", "news"));
}
}
add_filter("pre_get_posts", "custom_home_loop");
我有没有办法把这两者合并起来?我想做点什么
$query->set("post__not_in",$exclude);
, 但当我尝试的时候,那是行不通的。没有错误,帖子只是不断出现。我试着移动
$exclude
代码输入到
custom_home_loop
函数,但由于某种原因,我不断收到内存溢出错误。
SO网友:BA_Webimax
Untested:
function custom_home_exclude( $where = \'\' ) {
$exclude = array();
$newsQuery = new WP_Query (array(
"post_type" => "news",
"meta_key" => "post_to_blog",
"meta_value" => 1,
"meta_compare" => "!=",
"posts_per_page" => "-1",
));
while ($newsQuery->have_posts()) {
$newsQuery->the_post();
array_push($exclude, get_the_ID());
}
wp_reset_query();
$exclude = join(\',\', $exclude);
$where .= " AND `ID` NOT IN ($exclude)";
return $where;
}
function custom_home_loop($query) {
if ($query->is_main_query() && is_home()) {
$query->set("post_type", array("post", "news"));
add_filter( \'posts_where\', \'custom_home_exclude\' );
}
}
add_filter("pre_get_posts", "custom_home_loop");