如何修改CPT Calendar Widget插件,使其调用ACF日期字段而非发布日期
Got it, let's walk through how to adjust this plugin to work with your ACF date picker fields instead of the default post publish date.
First, a quick recap: WordPress' built-in calendar doesn't support Custom Post Types (CPTs), so you're using the CPT Calendar Widget—but right now it only pulls dates from post publish times, not the start/end dates you've set via Advanced Custom Fields. Here's how to tweak the code:
Step 1: Locate the Query Logic in the Plugin
Open the main plugin code file and find the section where it fetches CPT posts (usually a function that sets up a WP_Query or pulls posts for the calendar display).
Step 2: Replace the Date Query with ACF Fields
Instead of relying on the post_date field, we'll use ACF's meta fields to filter and fetch posts. Let's assume your ACF start date field key is event_start and end date is event_end—swap these with your actual field keys if they're different:
// Update the WP_Query arguments to target ACF date fields $args = array( 'post_type' => $cpt_types, // This variable should already exist in the plugin 'posts_per_page' => -1, 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'event_start', 'compare' => 'EXISTS' // Ensure the field has a value set ), array( 'key' => 'event_end', 'compare' => 'EXISTS' ) ) ); $calendar_posts = new WP_Query( $args );
Step 3: Map Posts to Calendar Dates Using ACF Values
Next, find the part of the code that assigns posts to specific calendar dates (it probably uses $post->post_date or get_the_date()). Replace that with logic that uses your ACF start/end dates:
// Loop through each fetched post if ( $calendar_posts->have_posts() ) { while ( $calendar_posts->have_posts() ) { $calendar_posts->the_post(); // Pull ACF date values for the current post $start_date = get_field( 'event_start', get_the_ID() ); $end_date = get_field( 'event_end', get_the_ID() ); // Convert dates to timestamps for easy date range iteration $start_ts = strtotime( $start_date ); $end_ts = strtotime( $end_date ); // Add the post to every date between start and end (inclusive) for ( $current_ts = $start_ts; $current_ts <= $end_ts; $current_ts += 86400 ) { $date_key = date( 'Y-m-d', $current_ts ); $calendar_events[ $date_key ][] = get_the_ID(); // Or store the full post object if needed } } wp_reset_postdata(); }
Step 4: Test and Adjust
Save your changes, then refresh your site to check the calendar. A few quick notes:
- Make sure your ACF date fields are set to a format that
strtotime()can parse (likeY-m-dorYmd—you can adjust this in the ACF field settings). - If you only use a single date field (no end date), remove the
event_endpart of themeta_queryand just map the post to the start date directly.
内容的提问来源于stack exchange,提问作者TechRemarker

