我怎么只显示最近10篇帖子中的1篇?

问题描述 投票:0回答:2

我的英语不好。对不起!

此代码用于高级自定义字段插件中的复选框。

我只希望从最近的10个帖子中仅显示1个帖子(随机)。

请帮助我。感谢

(('posts_per_page'=> 10)和('numberposts'=> 10)无法正常工作。

<?php
$gallery = array(
"offset" => "0",
'showposts' => '1',
'orderby'        => 'rand',
'meta_query' => array(
array(
'key' => 'postcat',
'value' => '"selection"',
'compare' => 'LIKE'
)));
// query
$qgallery = new WP_Query( $gallery );
?>  
<?php if( $qgallery->have_posts() ): ?>
<?php while( $qgallery->have_posts() ) : $qgallery->the_post(); ?>
<div class="fromgallery">
<a href="0" class="frgall">
<span class="frgdesc"><?php the_title() ?></span>
</a></div>
<?php endwhile; ?><?php endif; ?>
wordpress
2个回答
1
投票

尝试一下

$gallery = array(
'post_type'             => 'post',
'posts_per_page'        => 10,
'order'                 => 'DESC',
'no_found_rows'         => 'true',
'_shuffle_and_pick'     => 1
'meta_query' => array(
array(
'key' => 'postcat',
'value' => '"selection"',
'compare' => 'LIKE'
)));

我只更改您的代码。对于随机发一个帖子,您需要使用'_shuffle_and_pick'=> 1,'posts_per_page'=> 10个帖子来自10个帖子,而'order'=>'DESC'是最新帖子。对于自定义'_shuffle_and_pick',您需要添加

add_filter( 'the_posts', function( $posts, \WP_Query $query )
{
    if( $pick = $query->get( '_shuffle_and_pick' ) )
    {
        shuffle( $posts );
        $posts = array_slice( $posts, 0, (int) $pick );
    }
    return $posts;
}, 10, 2 );

0
投票

要显示随机帖子,请使用以下脚本:

$args = array(
    'post_type'      =>  'post',
    'posts_per_page'        => 10,
    'orderby'               => 'date',
    'order'                 => 'DESC',
    'no_found_rows'         => 'true',
    '_shuffle_and_pick'     => 1
    'post_status'           =>  'publish',
    'meta_query'            => array(
                         array(
                           'key' => 'postcat',
                           'value' => '"selection"',
                           'compare' => 'LIKE'
                         )
                   )
    );

$the_query = new WP_Query( $args );
//check is post found 
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo  get_the_title(); 
    }
    wp_reset_postdata();
} else {
    echo 'no posts found';
}

我希望它将对您有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.