1

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?

  • Is this for a main query or a secondary query? – birgire Jul 15 '15 at 19:50
2

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+.

| improve this answer | |

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.