marcbelletre/acf-rrule

高级自定义字段(ACF)的RRule字段

安装: 38

依赖项: 0

建议者: 0

安全: 0

星级: 15

关注者: 2

分支: 5

开放问题: 3

类型:wordpress-plugin

v1.5.0 2024-02-14 10:47 UTC

README

在单个ACF字段中创建重复规则,并使用 simshaun/recurr 包检索所有日期。

ACF RRule Screenshot

用法

<?php $rrule = get_field('rrule'); ?>

RRule字段返回一个具有以下属性的数组

高级用法

此插件的一个常见用途是为事件创建日程表式显示。这是我通常的做法。

在以下示例中,我们假设您有一个名为 rrule 的ACF RRule字段的 event 自定义帖子类型。

第一步是使用 acf/save_post 钩子将第一个和最后一个日期保存到数据库中。这对于稍后查询事件是必要的。

/**
 * 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'));
});

然后您可以使用 start_dateend_date 元值在一个自定义的 WP_Query 中,以过滤在指定日期之间可能发生的活动。

$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);
}

当然,这是一个非常基础的示例,您将需要根据您的用例进行修改。

测试

vendor/bin/phpcs -p . --standard=PHPCompatibilityWP --extensions=php --runtime-set testVersion 7.2-