0

In my archive I have tipical loop

if ( have_posts() ) :
    /* Start the Loop */
    while ( have_posts() ) : the_post();
       get_template_part( 'template-parts/content', get_post_format() );
    endwhile;
    wp_reset_postdata();
else :
    get_template_part( 'template-parts/content', 'none' );
endif; 

And in my sidebar I have a plugin widget which also calls new wp_query to display the recent posts.

$query = new WP_Query( 
    apply_filters( 
        'widget_posts_args', 
        array( 
            'posts_per_page' => $number, 
            'no_found_rows' => true, 
            'post_status' => 'publish', 
            'ignore_sticky_posts' => true 
        ) 
    )
);

So far so good. But then I need to add filter for my categories to display and custom posts types:

function mvp_add_custom_types( $query ) {
    if( is_category() || is_tag() || is_date() && empty( $query->query_vars['suppress_filters'] ) ) {
        $query->set( 'post_type', array(
            'post', 'nav_menu_item', 'mvp_projects'
        ));
        return $query;
    }
}
add_filter( 'pre_get_posts', 'mvp_add_custom_types' );

Which suddenly starting to break the other query. How can I use both of this queries with the filter applied to only theme related(the other query is from a plugin)?

1

I'm not entirely sure, but it looks like you need another conditional in your filter. Right now, it filters all content looking for category, tag or date that don't have the nav_menu_item, mvp_projecvts query variable set for post types. Perhaps you could add a filter to check if some variable is set and only filter if the variable exists.

$archive_ok= true; then in your filter: if ($archive_ok) { do stuff } $archive_ok=false;

It's a clunky solution and I am sure there are better answers, but it might work in a pinch.

0

I got this sorted, by adding additional contional statement and wrapped OR statements in brackets:

function mvp_add_custom_types( $query ) {
    if( ( is_category() || is_tag() || is_date() ) && $query->is_main_query() && empty( $query->query_vars['suppress_filters'] ) ) {
        $query->set( 'post_type', array(
            'post', 'nav_menu_item', 'mvp_projects'
        ));
        return $query;
    }
}
add_filter( 'pre_get_posts', 'mvp_add_custom_types' );

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.