最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

loop - Meta query compare for ID's greater than specific ID

programmeradmin0浏览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

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

Share Improve this question asked Sep 23, 2019 at 9:27 LeopoldLeopold 76 bronze badges 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 Commented 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 Commented 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? – Jacob Peattie Commented 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 Commented Sep 23, 2019 at 10:32
  • For that use case you should use the post date. – Jacob Peattie Commented Sep 23, 2019 at 10:42
 |  Show 1 more comment

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论