使用缩略图查询粘帖

时间:2015-07-16 作者:Nikita

我需要显示最多5个有缩略图的最新粘性帖子。我需要准确统计显示的帖子数量。我尝试用meta\\u查询排除没有缩略图的粘性帖子,但没有成功。

$sticky = get_option(\'sticky_posts\');

if (empty($sticky)) {
    return;
}

$counter = 1;

$r = new WP_Query(array(
    \'posts_per_page\' => 5,
    \'post__in\'       =>  $sticky,
    \'meta_query\' => array(
        array(
            \'key\'     => \'_thumbnail_id\',
            \'compare\' => \'EXISTS\',
        ),
    ),
    \'post_status\'    => \'publish\',
    \'orderby\'        => \'post__in\',
    \'post_type\'      => array( \'post\' ),
));


if ($r->have_posts()) :

    echo \'<section class="header-sticky-posts \'.$post_count.\'">\';

        while ( $r->have_posts() ) : $r->the_post();

            echo \'<div class="header-sticky-post">\';
                // Post content
            echo \'</div>\';

        $counter++; 
        endwhile;

    echo \'</section>\';

endif;
wp_reset_postdata();

2 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

您需要设置ignore_sticky_poststrue 在查询参数中。这样,您可以排除粘性帖子,只关注传递给的帖子ID的数组post_in

\'ignore_sticky_posts\' => true,
编辑如果这没有多大意义,请参见my answer here 对于类似的问题,我已经做了更好的解释。一定要去看看

代码

$r = new WP_Query(array(
    \'posts_per_page\' => 5,
    \'post__in\'       =>  $sticky,
    \'meta_query\' => array(
        array(
            \'key\'     => \'_thumbnail_id\',
            \'compare\' => \'EXISTS\',
        ),
    ),
    \'post_status\'    => \'publish\',
    \'orderby\'        => \'post__in\',
    \'post_type\'      => array( \'post\' ),
    \'ignore_sticky_posts\' => true,
));

SO网友:Puni

您所做的是正确的,除非您很粗心,或者您只是从其他地方复制了代码,然后粘贴到其中而没有修改它。

<?php
$sticky = get_option(\'sticky_posts\');

if (empty($sticky)) {
    return;
}

$counter = 1;

$posts = new WP_Query(array(
    \'posts_per_page\' => 5,
    \'post__in\'       =>  $sticky,
    \'meta_query\' => array(
        array(
            \'key\'     => \'_thumbnail_id\',
            \'compare\' => \'EXISTS\',
        ),
    ),
    \'post_status\'    => \'publish\',
    \'orderby\'        => \'post__in\',
    \'post_type\'      => array( \'post\' ),
));


if ($posts->have_posts()) :

        while ( $posts->have_posts() ) : $posts->the_post();

                if ( has_post_thumbnail() ) :
                    echo \'<section class="header-sticky-posts\'.$counter.\'">\';
                    echo \'<div class="header-sticky-post">\';
                            the_post_thumbnail();
                    echo \'</div>\';
                    echo \'</section>\';
                    $counter++; 
                endif;

        endwhile;

endif;
wp_reset_postdata();

结束

相关推荐

WP_QUERY LOOP ELSE语句未执行

我有两个WP_query 在我的frontpage中循环。php文件:<div id=\"aanbod\"> <div class=\"container-fluid section-name-cont\"> <div class=\"container\"> <div class=\"row\"> <div class=\"col-xs-12 section-name\"