簡體   English   中英

Wordpress查詢只顯示粘貼帖子

[英]Wordpress query to show only sticky posts

以下是我的wordpress查詢,其中我只想顯示粘貼的帖子,但查詢沒有顯示任何帖子。 另外我將兩個帖子設置為粘性,以便檢查部分!!! 請告訴我如何修改此查詢,以便它只顯示粘貼的帖子

<?php 
   $wp_query = null; 
  $wp_query =  new WP_Query(array(
 'posts_per_page' => 2,
 //'paged' => get_query_var('paged'),
 'post_type' => 'post',
'post__in'  =>  'sticky_posts',
 //'post__not_in' => array($lastpost),
 'post_status' => 'publish',
 'caller_get_posts'=> 0 ));

  while ($wp_query->have_posts()) : $wp_query->the_post(); $lastpost[] = get_the_ID();
?>

查詢僅顯示粘貼帖子:

// get sticky posts from DB
$sticky = get_option('sticky_posts');
// check if there are any
if (!empty($sticky)) {
    // optional: sort the newest IDs first
    rsort($sticky);
    // override the query
    $args = array(
        'post__in' => $sticky
    );
    query_posts($args);
    // the loop
    while (have_posts()) {
         the_post();
         // your code
    }
}

query_posts()函數在設置當前查詢之前不創建新的WP_Query(),這意味着這不是最有效的方法,並將執行額外的SQL請求

使用'pre_get_posts'掛鈎是安全的,比如

function sticky_home( $query ) {

    $sticky = get_option('sticky_posts');

    if (! empty($sticky)) {
        if ( $query->is_home() && $query->is_main_query() ) {
             $query->set( 'post__in', $sticky );
        }
    }

} add_action( 'pre_get_posts', 'sticky_home' );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM