1

I know that pre_get_posts can be used to target a query on the main site, custom post types and pages. But is there a way to target a query in a sidebar? Right now, I'm using 'is_page_template()` but it's only using the main query.

Code on my functions.php template:

function opby_query( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
    $query->set('tax_query', array(
    array('taxonomy' => 'category',
    'field' => 'slug',
    'terms' => array( 'podcast-control-daily' ),
    'operator'=> 'NOT IN'
    ),
    array('taxonomy' => 'post_format',
    'field' => 'slug',
    'terms' => array( 'post-format-status' ),
    'operator'=> 'NOT IN')
    )
    );
    $query->set( 'posts_per_page', 15 );
}
if ($query->is_page_template('sidebar.php')) {
    $query->set( 'tax_query', array(
    array('taxonomy' => 'category',
    'field' => 'slug',
    'terms' => array( 'podcast-control-daily' ),
    'operator'=> 'IN'
    )));
    $query->set( 'posts_per_page', 5 );
}
return $query;
}
add_action( 'pre_get_posts', 'opby_query' );

The sidebar is using the default loop:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<?php the_title();?><br>

<?php endwhile; else : ?>
<?php endif; ?>
  • The default loop is the main query. If you want a second query that does something different why not just create a new query. You seem to be repeating the main query everywhere then filtering with pre_get_posts rather than just creating new queries. – Jacob Peattie Feb 27 '18 at 8:53
  • I'm trying to keep everything under one query and that's the purpose of pre_get_posts is that you can target the main_query and a query on pages.php and another query on a custom_post_type all without having to set a new query. – Gregory Schultz Feb 27 '18 at 9:29
2

I think you can achieve this by adding a query var. And then you can use something in pre_get_posts like this:

if ( get_query_var( 'your_var' ) ) {
    // do something
}

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.