1

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.

0

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");
  • 1
    I get this error: Fatal error: Allowed memory size of 267386880 bytes exhausted (tried to allocate 523800 bytes) in /home/bernst0/public_html/wp-includes/query.php on line 3636 – JacobTheDev Aug 13 '14 at 20:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.