首先:可能有一个插件可以处理您想要实现的目标。如果您需要一个简单的活动日历,我几乎可以肯定这可以使用现有的插件来完成。在我的脑海中,MyCalendar 就是这样一个插件。在自己开始编写代码之前,您可能需要搜索 wordpress plugin directory 以获取更多选项。
话虽如此,如果你不能避免自己构建这个,因为你的情况是专门的,这应该让你开始:
要么使用custom fields 添加开始和结束日期的额外元数据,要么将事件设为自己的custom post type。详细解释自定义帖子类型的使用超出了简洁 SO 答案的范围。
如果您选择添加两个名为 start 和 end (或类似)的自定义字段的更简单方法,则必须将 php 脚本作为通过您的服务器进行 cronjob 或让我们使用 WP-Cron Functions 将当前时间与开始和结束日期进行比较,并相应地更改类别。
为了给你提供一些有用的代码(将进入你自己编写的插件),下面的 php sn-p 应该为你指明正确的方向:
register_activation_hook(__FILE__, 'your_activation');
add_action('your_daily_event', 'change_categories');
function your_activation() {
$first_time = time(); // you probably want this to be shortly after midnight
$recurrence = 'daily';
wp_schedule_event($first_time, $recurrence, 'your_daily_event');
}
function change_categories() {
$old_name = 'Upcoming'; // category to delete
$taxonomy = 'category';
// fetch category ID (amongst other data) of 'Upcoming':
$term = get_term_by('name',$old_name, $taxonomy);
// fetch all posts in 'Upcoming' category:
$objects = get_objects_in_term($term->term_id,$taxonomy);
// the $objects array now contains the post IDs of all upcoming events
// now, let's loop through them to manipulate:
foreach($objects as $object) {
// get start date:
$key = 'start'; // the name of the custom field
$start = get_post_meta($object, $key, true); // start date
$todays_date = date('Y-m-d'); // get current date
// Assuming, your dates in the custom fields are formatted YYYY-MM-DD:
if ($start < $todays_date) {
// change category:
$new_name = 'Current';
wp_set_post_terms( $object, $new_name, $taxonomy, false );
}
}
?>
几点说明: