在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><?phpwp_reset_postdata();}
}
3. 確保分類和置頂文章設置正確
分類設置:確保你已經創建了所需的分類,并將文章歸類到該分類下。
置頂文章:在WordPress后臺,編輯文章時勾選“置頂”選項,將需要推薦的文章設置為置頂。
4. 注意事項
分類ID:將代碼中的你的分類ID替換為你實際需要的分類ID。
定時任務:WordPress的定時任務依賴于頁面訪問觸發,因此需要確保網站有一定流量,以保證定時任務能夠按時執行。
原文
http://wordpress.jianyes.com/jianzhan/473.html