sourcetip

get_posts를 사용하여 X(ID)보다 큰 게시물을 가져오는 방법

fileupload 2023. 9. 15. 21:17
반응형

get_posts를 사용하여 X(ID)보다 큰 게시물을 가져오는 방법

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

특정 태그에서 10개의 레코드만 가져오려고 하는데 ID가 숫자보다 작습니다.get_posts 인수로 이를 수행할 수 있는 방법이 있습니까?인수 배열에서 Greater Than, Less Than 또는 Not Like를 지정하려면 어떻게 해야 합니까?

고마워요...

X보다 낮은 ID의 게시물을 받고 싶다면 좋은 해결책:

$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를 받은 후 wp_query에 해당 ID를 추가해야 합니다.

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;

당신은 사용할 수 있습니다.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 );

모두 쿼리하고 쿼리 루프 내부에서 ID가 선택한 개수보다 크거나 작는지 확인해야 합니다.

질의 자체로는 그런 요청을 처리할 수 없다는 것을 알고 있습니다.

이것은 (적어도 수천 개의 정수를 SQL로 전달하는 것과 비교할 때) 가장 빠르고, 가장 효율적이며, 가장 안정적인 방법입니다.

$compId = 555;
$filterWhere = function(string $where, \WP_Query $query) use (&$compId): string {
    $where .= " AND `ID` > $compId";
    return $where;
};

add_filter('posts_where', $filterWhere, 10, 2);
$posts = get_posts([
    'posts_per_page' => 20,
    'suppress_filters' => false,
]);
remove_filter('posts_where', $filterWhere);

저는 웹 엔트위클러의 아이디어를 좋아하지만 반대 방향으로 사용하는 것을 좋아합니다.최신으로 알려진 ID를 설정하고 not_in 메서드를 사용하면 미래에 대비할 수 있습니다.555+를 원하는 경우 해결책은 다음과 같습니다.

$args['post__not_in'] = range(1, 555);

그리고 1-555를 원한다면:

$args['post__in'] = range(1, 555);

언급URL : https://stackoverflow.com/questions/10827671/how-to-get-posts-greater-than-x-id-using-get-posts

반응형