Simple way make events in WordPress without plugin
I had a task to add the ability to add events (date, title, description, etc.) from dashboard and output them in the right place. I installed some plugin, at the start, but it haven’t lived up to my expectations. Unfortunately, I don’t remember his name, but I remember that it had the highest rating. OK, no problem, we’ll can use clean code.
Problem: Make events in WordPress without plugin.
Solution: Actually, we'll still use one plugin — Advanced Custom Fields (ACF). But I think, if you implement HTML to WordPress, that you already using it. So, let's start, firstly we should be register new post type "event" and secondly we'll output posts in loop in the right place. Note! We should hidden all events that have date above current date.
Step 1. Register post type "event".
<?php
add_action( 'init', 'list_post_type', 0 );
function list_post_type() {
$labels = [
'name' => __( 'Events', 'base' ),
'singular_name' => __( 'Events', 'base' ),
'menu_name' => __( 'Events', 'base' ),
'parent_item_colon' => __( 'Parent Item:', 'base' ),
'all_items' => __( 'All Events', 'base' ),
'view_item' => __( 'View Item', 'base' ),
'add_new_item' => __( 'Add New Item', 'base' ),
'add_new' => __( 'Add New', 'base' ),
'edit_item' => __( 'Edit Item', 'base' ),
'update_item' => __( 'Update Item', 'base' ),
'search_items' => __( 'Search Item', 'base' ),
'not_found' => __( 'Not found', 'base' ),
'not_found_in_trash' => __( 'Not found in Trash', 'base' ),
];
$args = [
'labels' => $labels,
'supports' => [ 'title', 'editor', 'excerpt', 'thumbnail', 'custom-fields', 'page-attributes', 'author' ],
'show_in_rest' => true,
'hierarchical' => false,
'public' => true,
'menu_position' => 6,
'has_archive' => false,
'menu_icon' => 'dashicons-calendar-alt',
'rewrite' => [
'slug' => 'event',
'with_front' => true,
],
];
register_post_type( 'event', $args );
unset( $labels );
unset( $args );
}
Step 2. Sort and output events in the custom WordPress query.
<?php
...
$secondary_args = [
'post_type' => 'event',
'posts_per_page' => -1,
'fields' => 'ids',
];
$secondary_query = new WP_Query( $secondary_args );
$posts_ids = $secondary_query->posts;
$exclude_posts_ids = [];
foreach ( $posts_ids as $post_id ) {
if ( strtotime( current_time( 'F j, Y' ) ) > strtotime( get_field( 'start_date', $post_id ) ) ) {
$exclude_posts_ids[] .= $post_id;
}
}
$args = [
'post_type' => 'event',
'posts_per_page' => get_field( 'posts_per_page' ),
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_key' => 'start_date',
'post__not_in' => $exclude_posts_ids,
];
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post(); ?>
...
<?php endwhile;
wp_reset_postdata(); ?>
...
<?php else :
if ( get_field( 'no_events_found_message' ) ) {
echo '<p>' . get_field( 'no_events_found_message' ) . '</p>';
} else {
echo '<p>' . __( 'Currently there are no events to show here', 'theme_name' ) . '</p>';
}
endif;