$args = array('numberposts' => 10, 'tag' => 'my-tag', 'ID' => 555');
$posts = get_posts($args);
我只想从特定标签中提取 10 条记录,并且 ID 小于数字。有没有办法用 get_posts 参数做到这一点?如何在参数数组中指定大于、小于或不喜欢?
谢谢...
如果您想获取 ID 低于 X 的帖子,这是一个不错的解决方案:
$post_ids = range(1, 555);
$args = array('numberposts' => 10,
'tag' => 'my-tag',
'post__in' => $post_ids');
$posts = get_posts($args);
此处为girlieworks 提供道具:https ://wordpress.org/support/topic/wp_query-how-to-get-posts-with-and-id-lower-than?replies=7#post-8203891
您需要先获取 ID,然后将这些 ID 添加到 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;
您必须查询所有这些,并在查询循环中检查 id 是大于还是小于您选择的数字。
据我所知,查询本身无法处理此类请求。
我喜欢Web-Entwickler 的想法,但使用相反的方向(因为它在问题中)。如果您设置最新的已知 ID 并使用 not_in 方法,它甚至是面向未来的。所以我的解决方案是如果你想要 555+:
$args['post__not_in'] = range(1, 555);
如果你想要 1-555:
$args['post__in'] = range(1, 555);
您可以使用posts_where
过滤器来更改 SQL 查询,以将结果限制为 ID 小于(或大于)某个数字的帖子:
$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 );