php - 随机选择一个帖子,不重复

标签 php wordpress

我只需要从我的 WordPress 首页上的大约 300 个帖子中随机显示 1 个帖子。当我按刷新时,有时同一篇文章会出现两次或在其他刷新后很快出现。我可以实现类似 iTunes 随机播放模式的功能吗?我现在正在使用这段代码:

<?php
$args = array( 'numberposts' => 1, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : 
?>
<?php the_title(); ?>
<?php endforeach; ?>

最佳答案

这只是一个概念证明,但应该能让您走上正轨。重要提示:

  • 必须在任何 HTML 输出发生之前设置 cookie
  • 我使用 cookie 作为数组,也许它可以是逗号分隔的列表并使用 explodepost__not_in
  • 创建数组
  • 代码使用 PHP 5.3+ 匿名函数,如果运行较低版本则必须更改
  • 当没有设置 cookie 时,您必须进行微调,很可能,我们需要做的是在不使用 not_in 过滤器的情况下再次运行 get_posts
add_action( 'template_redirect', function()
{
    # Not the front page, bail out
    if( !is_front_page() || !is_home() )
        return;

    # Used in the_content
    global $mypost;

    # Set initial array and check cookie    
    $not_in = array();
    if( isset( $_COOKIE['shuffle_posts'] ) )
        $not_in = array_keys( $_COOKIE['shuffle_posts'] );

    # Get posts
    $args = array( 'numberposts' => 1, 'orderby' => 'rand', 'post__not_in' => $not_in );
    $rand_posts = get_posts( $args );

    # All posts shown, reset cookie
    if( !$rand_posts )
    {
        setcookie( 'shuffle_posts', '', time()-86400 );
        foreach($_COOKIE['shuffle_posts'] as $key => $value)
        {
            setcookie( 'shuffle_posts['.$key.']', '', time()-86400 );
            $id = 0;
        }
    }
    # Increment cookie
    else
    {
        setcookie( 'shuffle_posts['.$rand_posts[0]->ID.']', 'viewed', time()+86400 );
        $id = $rand_posts[0]->ID;
    }
    # Set the global, use at will (adjusting the 'bail out' above)
    $mypost = $id;
    return;

    ## DEBUG ONLY
    #  Debug Results - remove the return above
    echo 'current ID:' . $id . "<br />";
    if( !isset( $_COOKIE['shuffle_posts'] ) )
        echo 'no cookie set';
    else
        var_dump($_COOKIE['shuffle_posts']);

    die();
});

add_filter( 'the_content', function( $content )
{
    global $mypost;
    if( isset( $mypost ) )
        $content = '<h1>Random: ' . $mypost . '</h1>' . $content;
    return $content;
});

过滤器the_content只是一个示例。 全局 $mypost 可以在主题模板中的任何位置使用(在调整bail out之后)。

如果处理注册用户,我们可以将值存储在user_meta中,而不是cookie。 .

关于php - 随机选择一个帖子,不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19570119/

相关文章:

php - Symfony session 不可用异常

javascript - 在不刷新网页的情况下加载 MySQL 数据

php - 如何从 WooCommerce 产品页面上的面包屑中删除产品类别

php - 如何通过其键获取 WooCommerce 购物车项目数据数组?

php - 如何单独交叉引用数据库表?

php - 如何从另一个 php 脚本中删除一个 php 脚本?

php - Magento 使用集合进行 (OR)

php - 如果在循环中包含 PHP 中的文件,每次在循环中运行时它都会访问该文件吗?

php - 如何修复此错误 XML 解析错误 : not well-formed

php - 在 WP_Query 中获取 WooCommerce 订阅产品类型和特定类别