Filter Posts from the Main Query


I want to conditionally merge a custom post type with my posts post type, based on a custom field. If the field’s value is 1, then I want I need those custom posts to appear in the same loop as posts on the home page. I can combine the custom post type with the default posts post type, and I can create an array of post IDs to exclude with post__not_in, but I can’t figure out how to apply that to the main loop. Here’s my code for the index.php template below:

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()) {
        array_push($exclude, get_the_ID());
if (have_posts()) {
    while (have_posts()) {
        get_template_part("content", get_post_format());
if ($wp_query->max_num_pages > 1) {
    echo "<div class="pagination">";
    echo "</div>";

And here’s what I’m doing to show the custom post type in the main query in functions.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");

Is there a way for me to merge these two? I’d like to do something like $query->set("post__not_in",$exclude);, but that doesn’t work when I try it. No error, the posts just keep showing up. I tried moving the $exclude code in to the custom_home_loop function, but I keep getting a memory overflow error for some reason.

, , , , JacobTheDev 9 years 2014-08-13T10:48:55-05:00 0 Answers 81 views 0

Leave an answer