Site icon Hip-Hop Website Design and Development

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()) {
        $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>";
}

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.