0

I just want to grab all posts that have a greater value than a supplied post ID

'meta_query' => array(
    'relation' => 'AND',
    array(
        'key' => 'rid',
        'value' => $rid,
        'compare' => '=',
        'type' => 'numeric',
    ),
    array(
        'key'     => ID,
        'value'   => $last_id,
        'compare' => '>',
        'type'    => 'numeric'
    ),
),

So if $last_id is "350", I want to grab all posts with a higher ID than 350

6
  • So the meta key is ID? And is that 'key' => ID (i.e. unquoted "ID" / meta key) just a typo in the question?
    – Sally CJ
    Sep 23, 2019 at 10:12
  • "ID", ID, "post_id"...I don't know what I'm supposed to use. I just need to fetch all posts with a higher post id than the given post id ($last_id)
    – Leopold
    Sep 23, 2019 at 10:17
  • The post ID isn't meta. WP_Query doesn't support that type of query, because they're not supposed to be used in a way that would require it. Why do you need to query by ID? Sep 23, 2019 at 10:27
  • Because I have a page with a loop of posts and I'm running an ajax interval check to live update new posts so I'm grabbing the last post id in the list on the page and looking server side for any posts with a higher post id.
    – Leopold
    Sep 23, 2019 at 10:32
  • For that use case you should use the post date. Sep 23, 2019 at 10:42

1 Answer 1

1

You can use prepare:

global $wpdb;

$post_ids = [];
$last_id = 350;

$query = $wpdb->prepare(
    "
        SELECT ID
        FROM $wpdb->posts
        WHERE ID > %d
    ", $last_id );

$results = $wpdb->get_results( $query );

// it will convert the IDs from row objects to an array of IDs
foreach ( $results as $row ) {
    array_push( $post_ids, $row->ID );
}

//now you can set up your query
$custom_args = array(
    'posts_per_page' => 100,    
    'post__in' => $post_ids
    );


$custom_query = new WP_Query( $custom_args );

if( $custom_query->have_posts() ) :
    while( $custom_query->have_posts() ) : $custom_query->the_post();
        echo get_the_title() . '<br>';
    endwhile;
endif;

Reference

Note: You can change condition as per your requirement >, >=, <, <= etc.

2
  • Do I have to though?
    – Leopold
    Sep 23, 2019 at 10:37
  • I didn't get it :( Sep 23, 2019 at 10:40

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.