PHP code example of marcbelletre / acf-rrule

1. Go to this page and download the library: Download marcbelletre/acf-rrule library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

marcbelletre / acf-rrule example snippets


 $rrule = get_field('rrule'); 

/**
 * Save first & last occurrences of an event in database.
 *
 * @param  int|string  $post_id
 * @return void
 */
add_action('acf/save_post', function (int|string $post_id) {
    if (! $post_id || get_post_type($post_id) !== 'event') {
        return;
    }

    $rrule = get_field('rrule');

    update_post_meta($post_id, 'start_date', $rrule['first_date']->format('Y-m-d'));
    update_post_meta($post_id, 'end_date', $rrule['last_date']->format('Y-m-d'));
});

$startDate = date('Y-m-d'); // Today
$endDate = date('Y-m-d', strtotime('+1 month', strtotime($startDate))); // Today + 1 month

// Retrieve events starting before the end date
// and ending after the start date
$eventsQuery = new WP_Query([
    'post_type' => 'event',
    'posts_per_page' => -1,
    'post_status' => 'publish',
    'meta_query' => [
        'relation' => 'AND',
        [
            'key' => 'start_date',
            'compare' => '<=',
            'value' => $endDate,
            'type' => 'DATE',
        ],
        [
            'key' => 'end_date',
            'compare' => '>=',
            'value' => $startDate,
            'type' => 'DATE',
        ],
    ],
]);

// Instanciate an array for our list of dates
$dates = [];

while ($eventsQuery->have_posts()) {
    $eventsQuery->the_post();

    $recurrence = get_field('rrule');

    // Loop through the individual dates for the recurrence
    foreach ($recurrence['dates_collection'] as $datetime) {
        $date = $datetime->format('Y-m-d');

        if ($date < $startDate) {
            // If the date is before the start date, jump directly to the next one
            continue;
        } elseif ($date > $endDate) {
            // If the date is after the end date, break the loop
            break;
        }

        // Create the date if it doesn't exist yet
        if (! isset($dates[$date])) {
            // Each date will contain an array of events
            $dates[$date] = [];
        }

        // Use the event ID as key to avoid duplicates
        $dates[$date][$post->ID] = $post;
    }

    // Sort array by key
    ksort($dates);
}