Custom Mini Calendar using WordPress REST API

This Pro tutorial provides the steps to use WordPress REST API to fetch posts of an Event CPT that have the same Event Date custom field value as the selected date of a Flatpickr datetime picker.

Although Bricks is used in this tutorial, it can be implemented in any WordPress site.

The main functionality is provided as a custom plugin.

Here's the overall flow:

  1. We create an input HTML element having an ID of event-calendar on a Page. This will host the calendar.
  2. We place flatpickr's CSS and JS files in the custom functionality plugin and load them where needed.
  3. We also enqueue a custom JS file in which
    • a Flatpickr instance is created in an empty div on the page
    • onChange event handler is defined
    • in this handler, a HTTP GET request is sent to our WP REST API endpoint having a custom route of /eventspickr/v1/events/<date> using JS' fetch() function, passing the selected date as part of the URL.
  4. This request is sent to the callback, fetchEvents() specified in the register_rest_route() in plugin's functions.php.
  5. This runs a WP_Query and forms an array with the necessary event data: event name, featured image, and permalink URL, and sends the WP REST response.
  6. Back in the custom JS file, the response is received, formatted and injected into the DOM.
  7. The fetchEvents() function is called each time a user selects a date on the Flatpickr calendar.

Thus, whenever a user picks a new date on the calendar, your site dynamically fetches and displays the events for that date without reloading the page.

Step 1

Using a plugin or otherwise, create event CPT having event_date custom field of date type.

Add a few test events and set the event date for each.

Step 2

Create/edit a Page where you'd like to have the mini calendar.

In this example, let's go with "Sample Page".

Copy this JSON and paste to get:

Add this custom CSS in the page settings:

#event-data {
    gap: 1.5em;
}

#event-data .event {
    display: flex;
    flex-direction: column;
    gap: 0.4em;
}

#event-data .event img {
    height: 200px;
    border-radius: 4px;
}

Step 3

Download the finished plugin from the link below, upload it to your site and activate it.

This is a BricksLabs Pro tutorial.

For full access login below or create your BricksLabs Pro account

Instant access to 390+ Bricks code tutorials with BricksLabs Pro