Sample Code
$args = [
\'posts_per_page\' => 1,
\'orderby\' => \'rand\',
\'post_type\' => \'post\',
\'ignore_sticky_posts\' => true,
];
$r= new WP_Query( $args );
if( $r->have_posts() )
{
while( $r->have_posts() )
{
$r->the_post();
if ( has_post_thumbnail() ) {
echo \'<a href="\'. get_permalink($q->ID). \'">\'; the_post_thumbnail(); echo \' </a>\';
}
the_title();
the_Excerpt();
}
}
else
{
_e( \'Sorry no posts found!\' );
}
}
<小时>
i also used the transient API but didn\'t get any help , code with transient is $args = [
\'posts_per_page\' => 1,
\'orderby\' => \'rand\',
\'post_type\' => \'post\',
\'ignore_sticky_posts\' => true,
];
$q= new WP_Query( $args );
set_transient( $r, $q, 28800 );
$r = get_transient($code);
if( $r->have_posts() )
{
while( $r->have_posts() )
{
$r->the_post();
if ( has_post_thumbnail() ) {
echo \'<a href="\'. get_permalink($q->ID). \'">\'; the_post_thumbnail(); echo \' </a>\';
}
the_title();
the_Excerpt();
}
}
else
{
_e( \'Sorry no posts found!\' );
}
最合适的回答,由SO网友:Niels van Renselaar 整理而成
我不确定你想要完成什么,因为你没有指出你的目标。但经过一些猜测,我认为您正在尝试24小时显示一篇文章,然后随机选择一篇新文章。
如果是这种情况,那么您使用的瞬态错误。
/**
* First, try to check our transient for a daily post id
*/
if ( false === ( $my_post_id = get_transient( \'my_daily_post_id\' ) ) ) {
/**
* No daily post ID, so create one
*/
$args = array(
\'posts_per_page\' => 1,
\'orderby\' => \'rand\',
\'post_type\' => \'post\',
\'ignore_sticky_posts\' => true,
);
$random_posts = get_posts( $args );
$my_post_id = false;
if( $random_posts ) {
foreach( $random_posts AS $random_post ) {
/**
* The first on in our randomized array
*/
$my_post_id = $random_post->ID;
break;
}
}
/**
* Set a transient for 24h with the post ID
*/
set_transient( \'my_daily_post_id\', $my_post_id, 24 * HOUR_IN_SECONDS );
}
/**
* Use our 24h post ID to find the post
*/
$args = array(
\'p\' => $my_post_id,
\'post_type\' => \'post\',
\'ignore_sticky_posts\' => true,
);
$q = new WP_Query( $args );
if( $q->have_posts() ) {
while( $q->have_posts() ) {
$q->the_post();
if ( has_post_thumbnail() ) {
echo \'<a href="\'. get_permalink($q->ID). \'">\'; the_post_thumbnail(); echo \' </a>\';
}
the_title();
the_excerpt();
}
} else {
_e( \'Sorry no posts found!\' );
}