Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Wordpress查询仅显示粘性帖子_Php_Wordpress - Fatal编程技术网

Php Wordpress查询仅显示粘性帖子

Php Wordpress查询仅显示粘性帖子,php,wordpress,Php,Wordpress,下面是我的wordpress查询,其中我只想显示粘性帖子,但查询不显示任何帖子。我还将两个帖子设置为粘滞,以便检查该部分!!!。请让我知道如何修改此查询,以便它只显示粘贴的帖子 <?php $wp_query = null; $wp_query = new WP_Query(array( 'posts_per_page' => 2, //'paged' => get_query_var('paged'), 'post_type' => 'post',

下面是我的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(),这意味着这不是最有效的方法,也不会是最有效的方法

使用“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' );

嘿,我面临的最后一个问题是,当没有粘性帖子时,我会收到警告:-/请让我知道如何修复该部分?如果使用
,您不应该收到任何警告!如我所示,为空。但您可以尝试扩展此
if
以检查
是否为数组($sticky)