Search code examples
datewoocommercecustom-fields

Custom date field in woocommerce only years?


I have created a custom field in woocommerce where i want shopowners choose a year of publishing (books in this case). So far i have:

//Custom Product Date Field
woocommerce_wp_text_input(
    array(
        'id' => '_custom_product_date_field',
        'placeholder' => 'Publicatiedatum',
        'label' => __('Publicatiedatum:', 'woocommerce'),
        'type' => 'date',
        'date-type' => 'years'
        )
    );

How can i set the date-type to years, as the last key => value (date-type:years) is not working?


Solution

  • I was curious since I was looking for details on using the date field in a woocommerce custom field. I didn't need year only specifically but it was an interesting rabbit hole to run down.

    Trying to understand a bit more how woocommerce_wp_text_input creates these fields it started to become more apparent that supplying the type attribute simply passes it on to the HTML attributes. That said, these are standard HTML elements, not a wrapper of sorts that produces more fancy fields utilizing things like jQuery which seems like what the OP was expecting.

    Looking over the specs for the date-related HTML text input fields it becomes apparent that there is not an <input> of type="year" available in the spec. We are limited to the type's specified in the specs.

    I was able to successfully create a month input with the following:

          woocommerce_wp_text_input(
            [
              'id' => '_my_month',
              'label' => __('My month', 'woocommerce'),
              'value' => get_post_meta($post->ID, '_my_month', true),
              'type' => 'month',
              'custom_attributes' => [
                'min' => '2020-01',
              ],
            ]
          );
    

    So understandably, from what I can see, doing what you are asking isn't possible unless the HTML specifications add a year input or woocommerce provides a bandaid when specifying type as year. Hopefully this better explains how woocommerce_wp_text_input expects the data to be formatted and what is really supported.

    As an aside that might assist in completing the requirements of the original question through alternate means, you could attempt to implement a jQuery UI picker which supports year only. I however feel that the jQuery UI picker using year only is a bit clumsy being it provides a popup to simply choose a date from a dropdown AND the left/right pagination of the popup still pages through months while showing only years. You might as well just use a dropdown or a number field with the date min/max values you require, both have example code that can be seen in other answers on that aforementioned answer I linked.