How to apply filter inside a single wp_query?

I’ve got a special query on my homepage that returns posts from a custom taxonomy.

I’m trying to apply this filter for it.

Read More
add_filter( 'post_limits', 'my_post_limits' );

function my_post_limits( $limit ) {
                                if ( is_home() ) {
                                    return 'LIMIT 0, 3';
                                }
                                return $limit;
                            }

However, this is also applied to my other loop that’s further down the page, so I’m guessing it’s something that’s not supposed to be set globally. I don’t have much backend knowledge and can’t figure out how to apply a filter such as this only inside my custom query. Is this possible ?

This is how my full query looks :

add_filter( 'post_limits', 'my_post_limits' );
function my_post_limits( $limit ) {
if ( is_home() ) {
    return 'LIMIT 0, 3';
}
return $limit;
}

$args = array(
'post_type' => array('post','featured-post'),
'tax_query' => array(
    array(
        'taxonomy' => 'featured',
        'field' => 'slug',
        'terms' => 'featured-homepage'
    )

)
);
$slider_query = new WP_Query( $args );
if ( $slider_query->have_posts() ):

while ( $slider_query->have_posts() ) :
    $slider_query->the_post();
    $tip_post=get_post_type();
    if (get_post_type()=='post') {

        $thumb = wp_get_attachment_image_src(     get_post_thumbnail_id($post->ID), 'bones-thumb-1280' );
        $url = $thumb['0'];
  // posts are here
} elseif(get_post_type()=='featured-post') {
  // custom posts are here
} endwhile; else: endif;

Related posts

Leave a Reply

2 comments

  1. You should consider using the posts_per_page parameter as suggested by @Tamil.

    But in general you can also remove the filters you add.

    In your case you could remove it after your WP_Query() with

    add_filter( 'post_limits', 'my_post_limits' );
    $slider_query = new WP_Query( $args )
    remove_filter( 'post_limits', 'my_post_limits' );
    

    so it won’t affect later queries.

    You can read more about it here in the Codex:
    http://codex.wordpress.org/Function_Reference/remove_filter

  2. Try post_per_page argument

    $args = array(
    'post_type' => array('post','featured-post'),
    'tax_query' => array(
        array(
            'taxonomy' => 'featured',
            'field' => 'slug',
            'terms' => 'featured-homepage'
        )
    ),
    'posts_per_page' => 7
    );