Register and display events.
<?php
/**
* Register events post type.
*/
add_action('init', function() {
$labels = array(
'name' => _x('Events', 'post type general name'),
'singular_name' => _x('Event', 'post type singular name'),
'add_new' => _x('Add New', 'portfolio item'),
'add_new_item' => __('Add New Event'),
'edit_item' => __('Edit Event'),
'new_item' => __('New Event'),
'view_item' => __('View Event'),
'search_items' => __('Search Events'),
'not_found' => __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => '',
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title', 'editor', 'thumbnail'),
'rewrite' => true,
'show_in_nav_menus' => true,
);
register_post_type('events', $args);
});
?>
functions.php
Event template.
<?php
$event_date = get_post_meta(get_the_ID(), 'event_date', true);
if ($event_date) {
$event_date = date('M d, Y', strtotime($event_date));
echo $event_date;
}
?>
event.php
Events template.
<?php
$future = date('Ymd', strtotime("+1 year"));
$past = date('Ymd', strtotime("-1 year"));
$present = date('Ymd', strtotime("now"));
$args = array(
'future' => array(
'label' => 'Future Events',
'query_args'=>array(
'post_type' => 'events',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'event_date',
'value' => array($present, $future),
'type' => 'numeric',
'compare' => 'BETWEEN',
)
)
)
),
'past' => array(
'label' => 'Past Events',
'query_args' => array(
'post_type' => 'events',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'event_date',
'value' => array($past, $present),
'type' => 'numeric',
'compare' => 'BETWEEN',
)
)
)
)
);
foreach($args as $arg){
$q = new WP_Query($arg['query_args']);
printf('<h2>%s</h2>', $arg['label']);
if ($q->have_posts()) {
echo '<ul>';
while ($q->have_posts()) {
$q->the_post();
printf(
'<li><a href="%s">%s</a></li>',
esc_url(get_permalink()),
esc_html(get_the_title())
);
}
echo '</ul>';
} else {
echo '<p>There are no events at the moment.</p>';
}
}
wp_reset_postdata();
?>
events.php