标签: 随机推荐

  • wordpress隔24小时随机推荐一个指定分类下的置顶内容

    在WordPress中实现每隔24小时随机推荐一个指定分类下的置顶内容,可以通过以下步骤实现:

    1. 创建自定义函数

    在主题的functions.php文件中添加以下代码,用于创建一个定时任务,每隔24小时随机选择一个置顶文章并存储到选项中:

    function set_random_sticky_post() {
        // 获取指定分类ID下的置顶文章
        $sticky_posts = get_option('sticky_posts');
        $category_id = 你的分类ID; // 替换为你的分类ID
        $args = array(
            'post__in' => $sticky_posts,
            'cat' => $category_id,
            'orderby' => 'rand',
            'posts_per_page' => 1,
        );
        $query = new WP_Query($args);
        if ($query->have_posts()) {
            $query->the_post();
            // 将随机选择的文章ID存储到选项中
            update_option('random_sticky_post_id', get_the_ID());
        }
        wp_reset_postdata();
    }
    // 添加定时任务
    if (!wp_next_scheduled('set_random_sticky_post_event')) {
        wp_schedule_event(time(), 'daily', 'set_random_sticky_post_event');
    }
    add_action('set_random_sticky_post_event', 'set_random_sticky_post');

    2. 显示随机推荐文章

    在需要显示随机推荐文章的地方(例如侧边栏或首页),添加以下代码:

    $random_sticky_post_id = get_option('random_sticky_post_id');
    if ($random_sticky_post_id) {
        $post = get_post($random_sticky_post_id);
        if ($post) {
            setup_postdata($post);
            ?>
            <div class="random-sticky-post">
                <h3>随机推荐</h3>
                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                <?php the_excerpt(); ?>
            </div>
            <?php
            wp_reset_postdata();
        }
    }

    3. 确保分类和置顶文章设置正确

    分类设置:确保你已经创建了所需的分类,并将文章归类到该分类下。

    置顶文章:在WordPress后台,编辑文章时勾选“置顶”选项,将需要推荐的文章设置为置顶。

    4. 注意事项

    分类ID:将代码中的你的分类ID替换为你实际需要的分类ID。

    定时任务:WordPress的定时任务依赖于页面访问触发,因此需要确保网站有一定流量,以保证定时任务能够按时执行。