How to get Posts Greater Than X (ID) using get_posts

元气小坏坏 提交于 2019-12-06 06:23:20

问题


$args = array('numberposts' => 10, 'tag' => 'my-tag', 'ID' => 555');
$posts = get_posts($args);

I want to bring only 10 records from an specific tag and that the ID is less than a number. Is there any way to do this with the get_posts arguments? How can I specify Greater Than, Less Than or Not Like in the arguments array?

Thanks...


回答1:


A nice solution if you want to get the posts with an ID lower than X:

$post_ids = range(1, 555); 

$args = array('numberposts' => 10, 
'tag' => 'my-tag', 
'post__in' => $post_ids');

$posts = get_posts($args);

props to girlieworks here: https://wordpress.org/support/topic/wp_query-how-to-get-posts-with-and-id-lower-than?replies=7#post-8203891




回答2:


You need to get the IDs first, and then add those IDs to wp_query.

global $wpdb;

$post_ids = [];

// Get all the IDs you want to choose from
$sql = $wpdb->prepare(
    "
        SELECT ID
        FROM $wpdb->posts
        WHERE ID > %d
    ", 555 );

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

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

// Set up your query
$custom_args = array(
    'posts_per_page' => 10,
    'tag' => 'my-tag',
    'post__in' => $post_ids
    );

// Do the query
$custom_query = new WP_Query( $custom_args );

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



回答3:


You would have to query all of them, and inside the query-loop check if the id is greater or less than the number of your choice.

As for as I know the query itself can't handle such requests.




回答4:


You could use the posts_where filter to alter the SQL query to restrict the results to posts with ID lower (or greater) than a certain number:

$args   = [
    'tag'              => 'my-tag',
    'posts_per_page'   => 10,
    // Required: posts_where is not triggered without setting suppress_filters to false.
    'suppress_filters' => false,
];
$max_id = 155;

$filter_handler = function( $where ) use ( $max_id ) {
    global $wpdb;

    return $where . $wpdb->prepare( " AND {$wpdb->posts}.ID < %d", $max_id );
};

add_filter( 'posts_where', $filter_handler );

$posts = get_posts( $args );

remove_filter( 'posts_where', $filter_handler );


来源:https://stackoverflow.com/questions/10827671/how-to-get-posts-greater-than-x-id-using-get-posts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!