How to show random post type and category wordpress

廉价感情. 提交于 2019-12-12 03:15:34

问题


I have a piece of code to show a random post type of specific category, it show one post but it does now show random, I wish to show a random post every single time the user refresh this page, any advice and suggestions will be greatly ppreciated.

Thansk :)

    <?php

global $post;
$args = array(
    'post_type'=>'topics',
    'showposts'=>'1',
    'cat'=> 8,
    'orderby' => 'rand'
);

$query = 'orderby=rand';
$my_query = new WP_Query($args);?>
<?php 
while ($my_query->have_posts()) : $my_query->the_post();?>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>

<?php endwhile; 
wp_reset_query(); ?>

回答1:


Hi Use this code for getting random posts..It works for me !!!

<h1>Random Posts</h1>
<ul>
 <?php
$args = array( 'posts_per_page' => 5, 'orderby' => 'rand','category' =>'8','post_type' => 'topics' );
$rand_posts = get_posts( $args );
foreach ( $rand_posts as $post ) : 
  setup_postdata( $post ); ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; 
wp_reset_postdata(); ?>
</ul>

Here it displays a list of 5 posts selected randomly by using the MySQL RAND() function for the orderby parameter value



来源:https://stackoverflow.com/questions/28087599/how-to-show-random-post-type-and-category-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!