我正在玩WordPress,我对PHP没有任何想法.我试图使用WordPress的get_posts()函数获取一些随机帖子我的代码是这样的
<?php
args1 = array( 'numberposts' => 12 ,'orderby' => 'rand');
$rand_posts1 = get_posts( $args1);
foreach( $rand_posts1 as $randpost1 ) : ?>
<?php the_title(); ?>
<?php endforeach; ?>
Run Code Online (Sandbox Code Playgroud)
但是这个代码只返回12次相同的帖子,这是最新的帖子.我无知究竟我做错了什么.
任何人都可以帮我纠正我的错误或指出我的问题.
小智 6
试试这个吧
<?php
$args1 = array( 'numberposts' => 12 ,'orderby' => 'rand');
global $post;
//save the current post
$temp=$post;
$rand_posts1 = get_posts( $args1);
foreach( $rand_posts1 as $post ) ://yes this is required, we need $post in setup_postdata
setup_postdata($post); ?>
<?php the_title(); ?>
<?php endforeach;
$post=$temp;//restore current page
?>
Run Code Online (Sandbox Code Playgroud)
那样做.另请查看get_posts