嗨,我正在试着设置24小时的帖子,随着它的改变

时间:2017-04-13 作者:hailey

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!\' );
}

1 个回复
最合适的回答,由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!\' );
}

相关推荐

Clear Transients

我已经为我的一个客户构建了一个自定义主题,我正在使用瞬态,以使站点运行更快。一周后,我在wp\\U选项中看到了大量瞬态记录(约360000条记录)。这使我怀疑瞬态不会从数据库中删除。如何删除该记录,以及如何删除?有什么好的教程吗?亲切的问候