2

We all know and its easy to get posts using WP_Query. We can filter, orderby etc. I am in a situation, where I would like to get all remaining posts after a post id, say 100. So what I need is to get all posts, ordered, filtered but only the remaining of 100.

Is there any tweak for this to achieve in WP_Query? If anybody gone through this before, advise me?

1
  • Is this for a main query or a secondary query?
    – birgire
    Commented Jul 15, 2015 at 19:50

1 Answer 1

4

You can try this:

$query = new WP_Query( 
    [ 
        'wpse_pid'        => 100,    // Our custom post id argument
        'wpse_compare'    => '>',    // Out custom compare argument (<,>,<=,>=,!=,<>)
        'posts_per_page'  => 100,    // Modify this to your needs             
    ] 
);

where we use the following plugin to support these two custom arguments:

<?php
/**
 * Plugin Name: Support for post ID filtering in WP_Query
 * Description: Uses wpse_pid and wpse_compare arguments
 * Plugin URI:  http://wordpress.stackexchange.com/a/193415/26350
*/
add_filter( 'posts_where', function( $where, $q )
{
    global $wpdb;

    if( $pid = $q->get( 'wpse_pid' ) )
    {
        // Get the compare input
        $cmp = $q->get( 'wpse_compare' );

        // Only valid compare strings allowed:
        $cmp = in_array( 
            $cmp, 
            [ '<', '>', '!=', '<>', '<=', '>=' ] 
        )
           ? $cmp
           : '=';  // default

        // SQL part
        $where .= $wpdb->prepare( " AND {$wpdb->posts}.ID {$cmp} %d ", $pid ) ;
    }
    return $where;

}, 10, 2 );

Note that this assumes PHP versions 5.4+.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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