- This topic is empty.
-
AuthorPosts
-
December 13, 2023 at 10:48 am #9922
tobyg
ParticipantI am using a Countdown element (probably Elementor) to show a countdown for a Time stored in an ACF field in a post. The Countdown needs a full DateTime – it wont work with just a time. The time will be fixed every day for 3 posts – 9am, 10am and 11am.
So I want to use php to update the field to today’s date but keep the time as it is in each post. This could happen on page load a function could check if the date was set to today and if not update it. But the key is the time has to stay the same.
The idea is that when a post is loaded it will always show the countdown to eg. 10am no matter what day it is.
#wordpress #acf
I’ve seen plenty of code to update the entire date field but not to maintain the time element.
December 13, 2023 at 11:32 am #9923tobyg
ParticipantSo this seems to work for a single post ID, how can I generalise out for all posts in a specific custom post type?
function update_acf_datetime_field() { // Assuming you have the post ID and your ACF field name $post_id = 120; // Replace with your actual post ID $field_name = 'date_time'; // Replace with your actual ACF field name // Get the current value of the ACF datetime field $current_datetime = get_field($field_name, $post_id); // If the field has a value, update only the date part to today if ($current_datetime) { $today_date = date('Y-m-d'); $updated_datetime = $today_date . substr($current_datetime, 10); // Preserve the time part update_field($field_name, $updated_datetime, $post_id); } } // Call the function to update the ACF datetime field update_acf_datetime_field();
December 14, 2023 at 2:42 am #9924loictheaztec
ParticipantTo generalize your code for all posts of a custom post type try the following:
function update_all_acf_datetime_fields() { $post_type = 'my_post_type'; // Here define your custom post type $field_name = 'date_time'; // Replace with your actual ACF field slug $today_date = date('Y-m-d'); // Get all posts IDs from a custom post type $posts_ids = get_posts( array( 'post_type' => $post_type, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids' ) ); // Loop through the posts IDs foreach( $posts_ids as $post_id ) { // Get the current value of the ACF datetime field $current_datetime = get_field($field_name, $post_id); // If the field has a value, update only the date part to today if ( ! empty($current_datetime) ) { $updated_datetime = $today_date . substr($current_datetime, 10); // Preserve the time part update_field($field_name, $updated_datetime, $post_id); } } } // Call the function to update the ACF datetime field update_all_acf_datetime_fields();
It should work…
-
AuthorPosts
- You must be logged in to reply to this topic.