从特定类别中随机选择一篇帖子?

时间:2017-08-01 作者:BuzzinBilly

我对word press很陌生,只在周末安装了它,我对HTML&;很在行;CSS,但PHP;Wordpress对我来说是陌生的。

我试图显示一个每天都在变化的特定类别的帖子,我到处搜索,发现下面的代码在一定程度上是可行的。

我似乎无法从类别编号中进行选择?

任何帮助或解释都将不胜感激。

    <?php
if ( false === ( $totd_trans_post_id = get_transient( \'totd_trans_post_id\' ) ) ) {
     $args = array(\'numberposts\' => 1, \'orderby\' => \'rand\');
     $totd = get_posts($args);
     $midnight = strtotime(\'midnight +1 day\');
     $timenow = time();
     $timetillmidnight = $midnight - $timenow;
     echo $midnight;
     echo ",".$timenow;
     set_transient(\'totd_trans_post_id\', $totd[0]->ID, $timetillmidnight);
} else {
    $args = array(\'post__in\' => array($totd_trans_post_id));
    $totd = get_posts($args);
}

foreach( $totd as $post ) : setup_postdata($post); ?>
    <div>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <?php the_content(); ?>
    </div>
<?php endforeach; ?>
EDIT 感谢您的建议,但我的现有代码似乎没有任何效果,它仍然会继续从所有类别中随机挑选一篇完整的帖子。

2 个回复
SO网友:giolliano sulit

您可以更改get_posts $args

示例:

$args = array(
    \'orderby\' => \'rand\',
    \'category_name\' => \'your_category\',
    \'showposts\' => 1
);

SO网友:Said Erraoudy

您可以在任何主题文件中使用以下代码段,也可以创建新的页面模板。在使用此代码之前,不要忘记替换要从中获取文章的类别ID。

<?php

// display random post from specific categories

$args = array(
    \'post_type\' => \'post\',
    \'post_status\' => \'publish\',
    \'cat\' => \'2, 6, 17, 38\', // category IDs
    \'orderby\' => \'rand\',
    \'posts_per_page\' => \'1\', // get 1 post only
    \'ignore_sticky_posts\' => 1,
);

$my_query = new WP_Query( $args );

// the loop
if ( $my_query->have_posts() ) :

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

        // display article
        get_template_part( \'content\', \'featured\' );

    endwhile;

endif;

wp_reset_postdata();
&燃气轮机;

结束

相关推荐

create shortcodes for posts

$query = new WP_Query(array( \'post_type\' => \'my_posttype\', \'post_status\' => \'publish\', \'posts_per_page\' => -1, \'orderby\' => \'title\', \'order\' => \'ASC\' )); while ($query->have_posts()) {&#