Support

Account

Home Forums Search Search Results for 'date picker'

Search Results for 'date picker'

topic

  • Solving

    Default value for datepicker

    Hi,

    I am trying to get a default value for datepicker, basically if field abc has no value, then it should have value xyz. If the field has value, then the value will be displayed. I have tried it with several solutions but I am no expert:

    add_filter('acf/load_field/name=date_of_birth', function ($field) {
        $field['default_value'] = date('d.m.Y');
        return $field;
    });

    or

    $goempty = '---';
    $defaultdateofbirth = get_field('date_of_birth');
    if (empty($defaultdateofbirth)) {
    update_field('date_of_birth', '---');
    } else {
    update_field('date_of_birth', $goempty);
    }

    The second one adds the today’s date and overwrites everything else.

    Can someone help me figure out a solution for that? Thanks!!

  • Unread

    Calculate Number of Years Between Two Date Pickers

    I have seen examples that show the number of years between a date picker and the current date but I am using a date of birth and date of passing to calculate the age of the person when they passed away.

    Any ideas how this can be achieved?

    Could I modify the below?

    
    <?php
    if(get_field('date_of_birth')) {
    $date = get_field('date_of_birth');
    $birthday = new DateTime($date);
    $interval = $birthday->diff(new DateTime);
    ?>
    <p>Age: <strong><?php echo $interval->y; ?></strong></p>
    <?php } ?>
    
  • Helping

    Bug with hasDatepicker

    Hello,

    ACF plugin conflicts with another plugin (RnB – WooCommerce Booking & Rental Plugin). I can’t use RnB’s calendar because ACF is adding its own on top of it with the hasDatepicker class. Would you have a solution to turn off ACF’s schedule so that I can use RnB’s schedule?

    Thank you !

  • Solved

    Hide past posts.

    Hello and thanks for a great plugin. I probably should not post here since I have no knowledge of PHP, but I hope it’s not too much of a bother.

    I’ve created a custom post type called Event and then a custom field with date picker. With the help of a code example in the documentaion on here I was able to sort the events by their date from the date picker field. I added the code to functions.php

    function my_pre_get_posts( $query ) {
    	
    	// do not modify queries in the admin
    	if( is_admin() ) {
    		
    		return $query;
    		
    	}
    	
    
    	// only modify queries for 'event' post type
    	if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'event' ) {
    		
    		$query->set('orderby', 'meta_value');	
    		$query->set('meta_key', 'start_date');	 
    		$query->set('order', 'ASC'); 
    		
    	}
    	
    
    	// return
    	return $query;
    
    }
    
    add_action('pre_get_posts', 'my_pre_get_posts');

    I wonder if it would be possible to have a similar function for hiding past posts/events and only show current day and forward? When looking around I did find code that seemed to do this, but I was not able to change it so it would work or make it into a function.

    Thank you in advance.

  • Unread

    Prefilled Datepicker field with posts publish date

    Hi,

    my datepicker field should only auto filled with the post publish date if nothing insert manually.

    Can anyone help me out?

    EDIT:
    OMG… No it’s workig. I put this code in my functions.php.

    For everyone who search for this:

    add_action( 'save_post', 'set_post_sortdate', 10,3 );
    function set_post_sortdate( $post_id, $post, $update ) {
        // Only want to set if this is a new post!
        if ( $update ){
            return;
        }
    
        // Only set for post_type = post!
        if ( 'post' !== $post->post_type ) {
            return;
        }
    
        // Get the default term using the slug, its more portable!
        $sortdate = get_the_date('Y-m-d', $post_id);
    
        $field_key = "YOUR_FIELD_NAME";
        $value = $sortdate;
        update_field( $field_key, $value, $post_id );
    }
  • Solving

    Create date archive page with Date Field

    I used the date picker to set another date for the post.I want to use this date to create a new archive page and create links.It’s like the post date archive page.
    Do you have any references? Please help me.

  • Solved

    Populate select color from option to a page

    Hello everybody,
    I created a repeater field in options to manage my theme colors with two subfields.
    – the first one is text field : Label named -> nom_couleur
    – the second one is colorpicker field : Value named -> couleur
    I populated it to all my pages to have a color for each page->subpages.
    On my pages I have a select to chose the color I want to use ( Color 1, color 2, etc…)
    With the code below in my functions.php, populate works but I need to update page manualy to change color on front.
    Choice is kept on page select color field but color doesn’t change on the front.
    What I’m looking for is when I update a color value in options it updates also color on my pages without having to clic on update page button.
    I’m doing something wrong but I don’t find.
    Could you please help me on this.

    Here is my function :

    function acf_load_color_field_choices( $field ) {
        // reset choices
        $field['choices'] = array();
        // if has rows
        if( have_rows('couleurs', 'option') ) {
            // while has rows
            while( have_rows('couleurs', 'option') ) {
                // instantiate row
                the_row();
                // vars
                $label = get_sub_field('nom_couleur');
                $value = get_sub_field('couleur');
                // append to choices
                $field['choices'][ $value ] = $label;
            }
        }
        acf_update_field( $field);
        // return the field
        return $field;
    }
    add_filter('acf/load_field/name=couleur_page', 'acf_load_color_field_choices');
  • Solved

    wp_query how to order events by date then time

    I’m using ACF to build an events calendar and I was hoping for some help with ordering the events by its date then by a separate field for its time (I can’t switch to the date & time picker).

    The calendar has 5 relevant fields in use for this question.

    • Start Date
    • End Date
    • Start Time
    • End Time
    • All Day Event

    I’m currently ordering the events by start and end date using the code below.

      
    $today = date('Ymd');
    
    $events_args = array(
        'post_type' => 'events',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'meta_query' => [
          [
            'relation' => 'AND',
            [
                'relation' => 'OR',
                [
                  'key'		=> 'start_date',
                  'compare'	=> '>',
                  'value'		=> $today,
                ],
                [
                  'key'		=> 'end_date',
                  'compare'	=> '>',
                  'value'		=> $today,
                ]
            ]
          ]
        ],
        'meta_key' => 'start_date',
        'orderby' => 'meta_value',
        'order' => 'ASC'
      );
    
    $events = new WP_Query($events_args);
    

    But I want to then also order the events by start time as events are occasionally loading 1 December 1pm – 3pm – 1 December 9am – 12pm.

    As you can see the 2nd events time is before the first events because they’re not also being ordered by start time.

    Another factor in the mix is the fact that start and end time are optional as I’ve given the option of all day event.

    I appreciate this is a complex use case for wp_query but I’d really appreciate any help and thank you in advance.

  • Solving

    Extract and compare month from two date time picker fields

    For our review site we wish to display events for the duration of the event.
    Say an event starts July 1st, ends on July 4th, a user can select
    July 1st in the acf field ‘datum’ and
    July 4th in the acf field ‘eind_datum’.

    Front end this should then look like “1-4 Juli 2020” (in the Dutch language)
    However, if an event takes place from June 30th until July 4th it should look like this “30 Juni – 4 Juli 2020”.

    In order to get this done I came up with the code below to compare the month. Is it the same, then the month should only be displayed once. Is it different, both the months should be displayed. I got this partially working, but for the life of me I can’t get the compare month function to work.

    Anybody on here that can help ?

     <?php  
    
    $start_date = get_field('datum');
    $end_date = get_field('eind_datum');
    $startdatetime = DateTime::createFromFormat("Y-m-d H:i:s", $start_date);
    $enddatetime = DateTime::createFromFormat("Y-m-d H:i:s", $end_date);
    $first = $startdateTime->format('F');
    $second = $enddateTime->format('F');
    	
     if (get_field('eind_datum') and get_field('datum') and ($first == $second )) {
      echo  $start_date->format ('j'); echo "-"; echo $end_date->format ('j F Y') ;
     }
     elseif (get_field('eind_datum') and get_field('datum') and ($first != $second )) {
      echo  $start_date->format('j F'); echo "-"; echo $end_date->format ('j F Y') ; 
     }
     else {
      echo the_field('datum') ;
     }
     ?>

    I also had another variation, but sadly wordpress throws an error for this as well.

     <?php  
    	$start_date = get_field('datum', false, false);
        $start_date = new DateTime($start_date);
        $end_date = get_field('eind_datum', false, false);
        $end_date = new DateTime($end_date);
        $start_month = $start_date->format('F');
        $end_month = $end_date->format('F');
    	
     if (get_field('eind_datum') and get_field('datum') and ($start_month == $end_month )) {
      echo  $start_date->format ('j'); echo "-"; echo $end_date->format ('j F Y') ;
     }
     elseif (get_field('eind_datum') and get_field('datum') and ($start_month != $end_month )) {
      echo  $start_date->format('j F'); echo "-"; echo $end_date->format ('j F Y') ; 
     }
     else {
      echo the_field('datum') ;
     }
     ?>
  • Solved

    ACF Date picker + Woo + WP All Export

    I’ve setup an ACF date field (Delivery Date) attached to my WooCommerce orders. When I try to use WP All Export’s (WPAE) filtering options on the date field, it does not seem to be working properly. The indications here are:

    1. There is no “newer than” rule, unlike when you use the Order Date element.

    2. Regardless of the rule chosen for Delivery Date element, WPAE can’t find any result.

    So I’m asking the community for help. If you’ve used an ACF date field in the WooCommerce orders and tried to filter the export in WPAE, how did you get it to work?

    I’m running the latest versions of WP, ACF, Woo and WPAE.

    Thank you in advance.

  • Helping

    Datepicker only Month and Year

    Hi,

    it is possible that replace the included jQuery Datepicker with some other like Datepicker for Bootstrap.

    I want to have datepicker like in this demo youst month and year.

    KR. Toni

  • Helping

    How to transfer form Gutenberg-Block to another ACF-Field

    Hi

    I have registered an ACF field as a Gutenberg-Block.

    add_action('acf/init', 'my_acf_init');
    function my_acf_init() {  
        if( function_exists('acf_register_block_type') ) {
            acf_register_block_type(array(
                'name'                => 'event-date',
                'title'                => __('Veranstaltungs-Datum'),
                'description'            => __('Veranstaltungs-Datum'),
                'render_template'   => 'block-rendering/events_date.php',
                'icon'                => 'format-image',
                'keywords'            => array( 'Event' ),
                'mode'                 => 'edit',
                'supports'          => array('multiple' => false, 'className' => true ), 
                'post_types' => array('events',),
            ));
     
        }    
    }  

    It is a repeater field with a date picker (and other fields).
    Is there a way to automatically transfer the date from the Gutenberg block to another ACF field (not registered as a block)?

    Thank you all!
    Matthias

  • Solved

    Publish / Expire posts based on ACF date picker field

    Hi guys. Longtime ACF user here.

    Having an issue creating functions to publish and expire posts based on ACF date picker fields. Have tried all of the examples out here in the forums and elsewhere on the web, of which there are two types: those that use cron jobs and those that target transients.

    For the cron job examples, my cron fires, no errors in error log, yet nothing happens on the backend, i.e. code doesn’t execute. There are a number of variations on this code, and right now I’m at

    add_action( 'wp', 'publish_coupons_yo' );
    
    function publish_coupons_yo () {
        if ( ! wp_next_scheduled( 'publish_coupon_function' ) ) {
            wp_schedule_event( time(), 'hourly', 'publish_coupon_function'); //hourly for testing
        }
    }
    add_action( 'publish_coupon_function', 'publish_coupon_function_callback' );
    
    function publish_coupon_function_callback() {
    
        $date = date('Ymd'); // matches the date in DB
        $args = array(
            'post_type' => 'coupon', 
            'posts_per_page' => -1,
            'post_status' => 'draft',
            'meta_query' => array( 
              'relation' => 'OR',
                array (
                   'key'     => 'publish_coupon_date',
                   'value' => $date, 
                   'compare' => '=' 
                ),
              array (
                'key' => 'publish_coupon_date',
                'value' => $date,
                'compare' => '<'
              )
            ) // end meta_query
          ); // end $args
    
    $publishquery = new WP_Query($args);
      // if posts are returned, loop over them and set active flag to false
      if ($publishquery->have_posts()) {
        global $post;
        if( !is_object($post) ) 
         return;
        while ($publishquery->have_posts()) {
          $publishquery->the_post();
          wp_transition_post_status('publish', 'draft', $post->ID);
        } // end while have_posts
        
        wp_reset_postdata();
      } // end if have_posts
    } // end function
    

    No dice.

    Then there’s the transient function code out there, such as from this ACF forum thread and this gist

    // Expire events
    if ($expireTransient = get_transient($post->ID) === false) {
    	set_transient($post->ID, 'set for 1 minutes', 1 * MINUTE_IN_SECONDS );
    	$today = date('Y-m-d H:i:s', current_time('timestamp', 0));
    	$args = array(
    		'post_type' => 'events',
    		'posts_per_page' => 200,
    		'post_status' => 'publish',
    		'meta_query' => array(
    			array(
    				'key' => 'end_date_time',
    				'value' => $today,
    				'compare' => '<='
    			)
    		)
    	);
    	$posts = get_posts($args);
    	foreach( $posts as $post ) {
    		if(get_field('end_date_time', $post->ID)) {
    			$postdata = array(
    				'ID' => $post->ID,
    				'post_status' => 'draft'
    			);
    			wp_update_post($postdata);
    		}
    	}
    }

    This code dates back to 2016. As someone commented recently on the gist, this code throws an error PHP Notice: Trying to get property ‘post_type’ of non-object, and PHP Notice: Trying to get property ‘ID’ of non-object. Someone also posted the same problem to stackoverflow without a helpful response from anyone.

    I’m wondering if since these example codes are from a few years ago, if they are out of date now in 2020. No combination or tweaking of either of these has worked for me and I’ve been trying now for a couple of weeks. Any thoughts or consideration on these snips would be most appreciated, thanks in advance.

  • Unread

    Publish posts based on ACF date picker field

    Hi there. Longtime ACF user here. I’m trying to create two functions, one to publish posts based on ACF date picker field, the other to expire them on a date picker field. I’ve looked at all the forum topics on this and tried most of the existing code out there, yet can’t get anything to work.

    For examples using crons and not transients, the cron is firing correctly and no errors are logged in the error log. Here’s the code tried on that

    add_action( 'wp', 'publish_coupons_yo' );
    
    function publish_coupons_yo () {
        if ( ! wp_next_scheduled( 'publish_coupon_function' ) ) {
            wp_schedule_event( time(), 'hourly', 'publish_coupon_function'); //hourly for testing
        }
    }
    add_action( 'publish_coupon_function', 'publish_coupon_function_callback' );
    
    function publish_coupon_function_callback() {
    
        $date = date('Ymd'); // matches the date in DB
        $args = array(
            'post_type' => 'coupon', 
            'posts_per_page' => -1,
            'post_status' => 'draft',
            'meta_query' => array( 
              'relation' => 'OR',
                array (
                   'key'     => 'publish_coupon_date',
                   'value' => $date, 
                   'compare' => '=' 
                ),
              array (
                'key' => 'publish_coupon_date',
                'value' => $date,
                'compare' => '<'
              )
            ) // end meta_query
          ); // end $args
    
    $publishquery = new WP_Query($args);
      if ($publishquery->have_posts()) {
        global $post;
        if( !is_object($post) ) 
         return;
        while ($publishquery->have_posts()) {
          $publishquery->the_post();
          wp_transition_post_status('publish', 'draft', $post->ID);
        } // end while have_posts
        
        wp_reset_postdata();
      } // end if have_posts
    } // end function
    

    For the transients example in the ACF forums here and elsewhere on the web, I have the same problem as this guy who posted on stackexchange, and a person who commented on the Gist of that same code, namely that it throws a PHP Notice: Trying to get property ‘ID’ of non-object and PHP Notice: Trying to get property ‘post_type’ of non-object.

    Wondering if the code in these examples dating 2016 etc are out of date, since they used to seem to work for people but more recently are not.

    I’ve verified that the date output matches the server output format, so that’s not the issue. Fairly stumped. Any thoughts?

  • Helping

    Sorting custom post type using select menu

    Hi everyone!
    I really like the plugin, it is great.

    I have been pairing it with a custom post type displaying concert dates, I can get all my posts to work fine and I can use WP_Query and $args to filter/order them simply. I use a datepicker ACF field ‘date_selector’, and “orderby” to order them by date.

    Things got more complicated then…
    I am trying to create a basic select menu with 2 options that would help sorting/reordering the posts based on their date. Just changing the “orderby” value for now would be enough to understand the way it works.

    From the ACF documentation, I understand that you can use if( isset($_GET['your-option']) ) to get the URL parameter and then use that to make some changes in your arrays?

    Sorry if I am lost. Here is my code for the cpt:

    <?php	
    $today = date('Y-m-d H:i:s');
    $args = array(
            'post_type' => 'agenda',
            'posts_per_page' => 8,
            'meta_key' => 'date_selector',
            'orderby' => 'meta_value',
            'order' => 'DESC',
            'suppress_filters' => true,
            'lang' => '',
            'meta_query' => array(
                'relation' => 'AND',
                array(
                'key' => 'date_selector',
                'value' => $today,
                'type' => 'DATE',
                'compare' => '<',
                    )
            )
    )
            
    ?>
    
    <div class="filtering-box fl-2 on_w g_sm_mt">
        <p>Sort by:</p>
            <form action="<?php the_permalink(); ?>" method="get">
                <select name="filter" id="date-filter">
                    <option value="date-recent">Now</option>
                    <option value="to-come">To come</option>
                </select>
                <button type="submit" value="">Sort</button>
            </form> 
    </div>
    <wrapper class="events-container g_sm_mt">
    	            
    
    <?php 
        function my_pre_get_posts( $query ) {
    	// do not modify queries in the admin
    	if( is_admin() ) {
    		return $query;
    	}
    	
    	// only modify queries for 'event' post type
    	if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'agenda' ) {
    		// allow the url to alter the query
    		if( isset($_GET['date-recent']) ) {
    			
        $args = array(
            'post_type' => 'agenda',
            'posts_per_page' => 1,
                'meta_query' => array(        
                    'key' => 'date_selector',
                    'value' => $today,
                    'type' => 'DATE',
                    'compare' => '>',
                        )
                    );
                }
                	// return
    	return $query;
    
                }
    
            }
        
        add_action('pre_get_posts', 'my_pre_get_posts');
    
    ?>
    
    <?php //Query posts 
    $agenda_dates = new WP_Query( $args ); ?>
    	<?php if ($agenda_dates->have_posts()): ?>
    		<?php while ($agenda_dates->have_posts()): $agenda_dates->the_post();?>
    
    //my posts here...
    
    <?php endwhile;?>
    	<?php endif;?>
    
    <?php wp_reset_postdata();?>
    

    I got this far, it keeps working but the filter option does not change anything to the posts when I select the value “date-recent”. Sorry for this poor attempt, I am not good at php and do not understand how to implement the sorting option.

    I am not even sure about the syntax and where I should write the URL parameter condition if( isset($_GET['...'])).

    Can anyone of you help me with this?

    Thank you,
    Have a nice day!

  • Unread

    Add class to select2 field via Javascript

    I want to add a class to all select2 fields in a frontend form. I know this is done bij Javascript but I just don’t know what it is. Below I have the code for date and time pickers and stuff. Could someone provide me the add-on for select2 fields?

    // Customization to booking datepicker
    function yl_add_acf_field_class_via_javascript() {
    
    	?>
    	<script type="text/javascript">
    	(function($) {
    
    		// Check ACF
    		if(typeof acf === 'undefined')
    			return;
    		// Date picker & Google Maps compatibility
    		$('.acf-google-map input.search, .acf-date-picker input.input, .acf-time-picker input.input').addClass('uk-input');
    
    		// Clean errors on submission
    		acf.addAction('validation_begin', function($form){
    			$form.find('.acf-error-message').remove();
    		});
    
    		// Add alert alert-danger & move below field
    		acf.addAction('invalid_field', function(field){
    			field.$el.find('.acf-notice.-error').addClass('uk-alert uk-alert-danger').insertAfter(field.$el.find('.acf-input'));
    		});
    
    	})(jQuery);	
    	</script>
    
    	<?php
    
    }
    
    add_action('acf/input/admin_footer', 'yl_add_acf_field_class_via_javascript');
  • Unread

    How to get formatted date value from date field in an ACF front-end form?

    I am trying to get the formatted date of an ACF date field into a javascript variable. I am using a front-end form. This is the code I have now but does not seem to work.

    		acf.add_filter('date_picker_args', function(args, field) {
    			console.log("test"); //this doesn't even show up in the console for some reason
    			args['onSelect'] = function(dateText, inst) {
    				console.log("dateText"); //nothing logged here either
    		  	}
    		  	return args;
    		});
  • Unread

    date & time picker wrong date & time issue

    Hi

    we have installed ACF date & time picker.

    the problem we have now is we need to click on “NOW” to get the correct current date & time for our posts.

    if we do not click on “NOW” it will wrongly publish the post date & time

    example of what happens:
    we published the post at “September 16, 2020 09:09 pm” in our city.

    but unfortunately the post published at: “September 16, 2020 10:09 am”

    pls note that the server date & time and location are correct.

    thanks

    we are using this code now:

    add_action( ‘acf/save_post’, ‘set_submit_time’ );
    function set_submit_time($post_id) {
    update_field(‘entry_post_date’, date(‘Y-m-d H:i:s’), $post_id);
    }

    add_action(‘save_post’, ‘change_content’);
    global $post;
    global $wpdb;
    function change_content($post_id) {
    $datefield = get_post_meta($post_id,’entry_post_date’,true);
    $post_date = date(“Y-m-d H:i:s”, strtotime($datefield));
    $my_post = array();
    $my_post[‘ID’] = $post_id;
    $my_post[‘post_date’] = $post_date;

    remove_action(‘save_post’, ‘change_content’);
    wp_update_post( $my_post );
    add_action(‘save_post’, ‘change_content’);
    }

  • Solving

    Remove unused scripts/styles

    Hello everyone!

    I realized that I don’t need most of the code loaded in the frontend- actually not in the backend either – eg select2, datepicker, timepicker, etc

    Additionally, although I am using the Repeater component, I don’t use the sortable feature in the frontend only; I realize that this is a tough one because it might be required to load the component. It would be really great to implement such features on-demand although I guess the devs would focus on other, more important things first.

    So, the question is, can you deregister and/or dequeue scripts/styles that are not used?

  • Unread

    acf minutes increment

    I am basically looking for a way to set the increment of minutes to 15.

    This was asked and answered before over here:

    https://support.advancedcustomfields.com/forums/topic/time-picker-args/

    but it seems i can not make it work / can not make the connection. For example: the solution posted above features a data-key for the field that should be adjusted. I don’t have/ I don’t see such a data-key in my installation. Instead my date/time field looks like this:

    <div class="acf-date-time-picker acf-input-wrap" data-date_format="dd.mm.yy" data-time_format="HH:mm" data-first_day="1">
    
    <input type="hidden" id="acf-field_5f59016066f6f" class="input-alt" name="acf[field_5f59016066f6f]" value="2020-09-11 20:00:00"/>
    <input type="text" class="input" value="11.09.2020 20:00"/>
    
    </div>

    I hope somebody can pint me in the right direction…?

  • Solved

    Inline datetime pickers?

    Hey there,

    Is it possible to inline the jQuery UI datetimepicker so it doesn’t render as a popup? I’m loading a custom js file that updates the arguments (based off some other posts I found), but I can’t seem to do it. This is all backend on an options page BTW.

    Current code is:

    
    function extend(destination, source) {
    	for (var property in source)
    		destination[property] = source[property];
    	return destination;
    }
    
    acf.add_filter('date_time_picker_args', function( args, $field ){
    	
    	
    	var custom_args = {
            altField: $field,
    	};
        
    	args = extend(args, custom_args)
    	
    	return args;
    			
    });
    

    Based off the docs here: https://trentrichardson.com/examples/timepicker/ one of the demos has the datetimepicker altField set to put it inline.

    Like this:

    
    $('#alt_example_4').datetimepicker({
    	altField: "#alt_example_4_alt",
    	altFieldTimeOnly: false
    });
    

    Anyone have any ideas?

  • Solving

    WP 5.5 color picker breaks front-end form

    Hi there,

    I updated WP to 5.5 and I am using the latest version of ACF PRO, now when my front-end form loads a color picker field, the console throws the following error:

    Uncaught ReferenceError: wp is not defined on color-picker.js?ver=5.5:14

    Resulting in another error on acf-input.min.js?ver=5.9.0:1:

    Uncaught TypeError: e.wpColorPicker is not a function

    It doesn’t happen on the back-end though. It seems to be a problem on the Color picker script’s side. Other plugins face the same issue, but their temporary solutions don’t seem to work here.

    Is there any way to (temporarily) fix this for the acf_form function?

reply

  • I found a workaround:

    
    acf.addFilter('date_time_picker_args', function(args, field) {
    	if (args.timeFormat == 'H\\hhmm') {
    		args.timeFormat = "H'h'mm";
    		args.pickerTimeFormat = 'H:mm';
    	}
    	return args;
    });
    

    Setting args.timeFormat controls the combined date/time display in the main text input field after the user makes a selection. setting args.pickerTimeFormat controls what displays in the hour and minute dropdowns inside the picker.

  • For those struggling add a Circle (Radius, for a service or delivery area, etc.).. try the code below. This will accept an address for the map, the radius for the circle and the zoom level for the map, as well as the stroke and fill colors for the circle itself.

    NOTE: I have these fields created in a Flexible Content Field Layout, you would use get_field, instead of get_sub_field if you just add these fields to a page..

    Here are the fields I’m using, with the Name and Type of Field:
    Map / map field
    Radius / Text
    Zoom / Text
    Stroke Color / Color Picker
    Fill Color / Color Picker

    Here is the code in the flexible content include (you could add this directly to the page template if needed)

    
     <?php 
     $location = get_sub_field('map');
     $radius = (get_sub_field('radius') > 0) ? get_sub_field('radius') * '1609.344' : "";
     $zoom = get_sub_field('zoom');
     $strokeColor = get_sub_field('stroke_color');
     $fillColor = get_sub_field('fill_color');
    
     if( $location ): ?>
      <section class="wrapper bg-light">
        <div class="map">
          <div class="acf-map" data-zoom="<?php echo $zoom; ?>">
              <div class="marker" data-lat="<?php echo esc_attr($location['lat']); ?>" data-lng="<?php echo esc_attr($location['lng']); ?>"></div>
          </div>
        </div>
        <!-- /.map -->
      </section>
      <!-- /section -->
    
      <style type="text/css">
      .acf-map {
          width: 100%;
          height: 500px;
          margin: 0;
      }
    
      .acf-map img {
         max-width: inherit !important;
      }
      </style>
    
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBfQsg-s2IP33YI4cXaUrGrJ4gGl-NAyaY&callback=Function.prototype"></script>
      <script type="text/javascript">
    
      (function( $ ) {
    
        /**
         * initMap
         *
         * Renders a Google Map onto the selected jQuery element
         *
         * @date    22/10/19
         * @since   5.8.6
         *
         * @param   jQuery $el The jQuery element.
         * @return  object The map instance.
         */
        function initMap( $el ) {
    
            // Find marker elements within map.
            var $markers = $el.find('.marker');
    
            // Create gerenic map.
            var mapArgs = {
                zoom        : $el.data('zoom') || 16,
                mapTypeId   : google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map( $el[0], mapArgs );
    
            // Add markers.
            map.markers = [];
            $markers.each(function(){
                initMarker( $(this), map );
            });
    
            // Center map based on markers.
            centerMap( map );
    
            // Return map instance.
            return map;
        }
    
        /**
         * initMarker
         *
         * Creates a marker for the given jQuery element and map.
         *
         * @date    22/10/19
         * @since   5.8.6
         *
         * @param   jQuery $el The jQuery element.
         * @param   object The map instance.
         * @return  object The marker instance.
         */
        function initMarker( $marker, map ) {
    
            // Get position from marker.
            var lat = $marker.data('lat');
            var lng = $marker.data('lng');
            var latLng = {
                lat: parseFloat( lat ),
                lng: parseFloat( lng )
            };
    
            // Create marker instance.
            var marker = new google.maps.Marker({
                position : latLng,
                map: map
            });
    
            // Append to reference for later use.
            map.markers.push( marker );
    
            // If marker contains HTML, add it to an infoWindow.
            if( $marker.html() ){
    
                // Create info window.
                var infowindow = new google.maps.InfoWindow({
                    content: $marker.html()
                });
    
                // Show info window when marker is clicked.
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open( map, marker );
                });
            }
            <?php if($radius > '0'): ?>
    
              var circle = new google.maps.Circle({
                  strokeColor: "<?php echo $strokeColor; ?>",
                  strokeOpacity: 0.8,
                  strokeWeight: 2,
                  fillColor: "<?php echo $fillColor; ?>",
                  fillOpacity: 0.35,
                  map: map,
                  center: latLng,
                  radius: <?php echo $radius; ?>,
                  draggable: false
              });
    
            <?php endif; ?>
    
        }
    
        /**
         * centerMap
         *
         * Centers the map showing all markers in view.
         *
         * @date    22/10/19
         * @since   5.8.6
         *
         * @param   object The map instance.
         * @return  void
         */
        function centerMap( map ) {
    
            // Create map boundaries from all map markers.
            var bounds = new google.maps.LatLngBounds();
            map.markers.forEach(function( marker ){
                bounds.extend({
                    lat: marker.position.lat(),
                    lng: marker.position.lng()
                });
            });
    
            // Case: Single marker.
            if( map.markers.length == 1 ){
                map.setCenter( bounds.getCenter() );
    
            // Case: Multiple markers.
            } else{
                map.fitBounds( bounds );
            }
    
        }
    
        // Render maps on page load.
        $(document).ready(function(){
            $('.acf-map').each(function(){
                var map = initMap( $(this) );
            });
        });
    
      })(jQuery);
      </script>
    
    <?php endif; ?>
    
  • ok, i’ve got something better :

    1. first, the ‘disabled’ capacity of the acf fields is actually just directly the html ‘disabled’ attribute that acf adds to form elements that supports it
    2. so, for some acf fields it is prety simple, because the field is a simple input on which acf can add the ‘disabled’ attributes :
      • text
      • textarea
      • number
      • email
      • url
      • password (is actually using text render function)
      • date picker
      • date time picker (is actually using date-picker class)
      • time picker
      • select
    3. for some fields, the disabled attribute in html is a little bit more complicated, it is an array of elements :
      • radio
      • checkbox
    4. for the rest, it’s not natively supported by acf, and for some fields it would not make sens anyway (‘message’ for example). So if i want to disable them anyway, i found a simple and better way than checking for the _POST[‘acf’] :
      1. first, add a special property to the field object (ex. ‘client_side_disabled’)
      2. then use the ‘acf/pre_update_value’ filter to check if the field have this property, and in that case prevent to save it
      3. and last, use the ‘acf/field_wrapper_attributes’ filter to add an attribute to the wrapper : ‘inert’ -> it will prevent all focus, from tab and mouse, but it will not prevent the form element to be submit, hence the previous filter

    the code looks like this :

    
    /*
    * utility function, to check if the field contains the class 'disable_acf'
    * I added the class in the admin acf field panel, for each field i want to disable
    *
    */
    function is_acf_field_disabled($field) {
      if (!isset($field['wrapper'], $field['wrapper']['class'])) {
        return false;
      }
    
      $class = $field['wrapper']['class'];
      if (!str_contains($class, 'disable_acf')) {
        return false;
      }
    
      return true;
    }
    
    /*
    * filter the fields when they render, to disable them
    * acf have a way to do it for some fields
    * for the others, add a property that will allow to use other filters on them
    *   and only if it was render first (so it will not affect server side field updates) 
    *
    */
    function disable_acf_field($field) {
      if (!is_acf_field_disabled($field)) {
        return $field;
      }
    
      $type = $field['type'];
      if (in_array($type, array('text', 'textarea', 'number', 'email', 'url', 'password', 'date_picker', 'time_picker', 'select'))) {
        $field['disabled'] = 1;
      }
      else if (in_array($type, array('checkbox', 'radio'))) {
        if (!isset($field['choices'])) {
          return $field;
        }
        $choices = $field['choices'];
        $to_disable = array_keys($choices);
        // acf cast the strings, so do i
        // line 128 : advanced-custom-fields/includes/fields/class-acf-field-radio.php
        $to_disable = array_map(function($e){return (string)$e;}, $to_disable);
        $field['disabled'] = $to_disable;
      }
      else {
        $field['client_side_disabled'] = 1;
      }
    
      return $field;
    }
    add_filter('acf/load_field', 'disable_acf_field');
    
    /*
    * add 'inert' attribute to the wrapper of the field
    * it prevents all focus actions, keyboard and mouse
    * but it does not prevents to submit values, instead of 'disabled' attribute
    *
    */
    function change_acf_field_wrapper($wrapper, $field) {
      if (!isset($field['client_side_disabled'])) {
        return $wrapper;
      }
    
      error_log("+field: " . json_encode($field));
      $wrapper["inert"] = "true";
      return $wrapper;
    }
    add_filter('acf/field_wrapper_attributes', 'change_acf_field_wrapper', 10, 2);
    
    /*
    * if the field has property 'client_side_disabled'
    *   don't save it
    * it does not prevent updates with update_field() on server side
    *
    */
    function disable_other_acf_field($null, $value, $post_id, $field) {
      if (isset($field['client_side_disabled'])) {
        return false;
      }
    
      return $null;
    }
    add_filter('acf/pre_update_value', 'disable_other_acf_field', 10, 4);
    

    I think it’s better

Viewing 25 results - 126 through 150 (of 787 total)