seo站内优化包括,wordpress 分类描述,网站建设 长摊 无形资产,wordpress 本地服务器搭建xampp在WordPress中实现每隔24小时随机推荐一个指定分类下的置顶内容#xff0c;可以通过以下步骤实现#xff1a;
1. 创建自定义函数
在主题的functions.php文件中添加以下代码#xff0c;用于创建一个定时任务#xff0c;每隔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 classrandom-sticky-posth3随机推荐/h3a href?php the_permalink(); ??php the_title(); ?/a?php the_excerpt(); ?/div?phpwp_reset_postdata();}
}
3. 确保分类和置顶文章设置正确
分类设置确保你已经创建了所需的分类并将文章归类到该分类下。
置顶文章在WordPress后台编辑文章时勾选“置顶”选项将需要推荐的文章设置为置顶。
4. 注意事项
分类ID将代码中的你的分类ID替换为你实际需要的分类ID。
定时任务WordPress的定时任务依赖于页面访问触发因此需要确保网站有一定流量以保证定时任务能够按时执行。
原文
http://wordpress.jianyes.com/jianzhan/473.html