简体   繁体   English

Wordpress查询只显示粘贴帖子

[英]Wordpress query to show only sticky posts

Following is my wordpress query in which i want to show only sticky posts but the query is not showing any posts. 以下是我的wordpress查询,其中我只想显示粘贴的帖子,但查询没有显示任何帖子。 Also I set two posts as sticky so that part is checked!!!. 另外我将两个帖子设置为粘性,以便检查部分!!! Kindly let me know how to modify this query so it will only show the posts which are sticky 请告诉我如何修改此查询,以便它只显示粘贴的帖子

<?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();
?>

Query which will show only sticky posts: 查询仅显示粘贴帖子:

// 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
    }
}

The query_posts() function creates a new WP_Query() not before the current query is set up, meaning this is not the best efficient method and will perform extra SQL requests . query_posts()函数在设置当前查询之前不创建新的WP_Query(),这意味着这不是最有效的方法,并将执行额外的SQL请求

Use the 'pre_get_posts' hook to be safe, like 使用'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