Search code examples
wordpressdateshortcode

How can I display a desired date into a Wordpress page?


I'm trying to find a way to choose a date and display it into a Wordpress page. Simply put, that's the way this may operate:

  1. One or several pages are input a shortcode or a PHP code via PHP insert
  2. An operator/webmaster chooses a date from let's say a calendar or drop down
  3. This date (formatted) shows into the pages that have the shortcode/PHP code

I do not want automatic or current date which I can do with this plugin. Can anybody help achieve this with a plugin or a PHP snippet?


Solution

  • Display a custom date field in Settings->Reading:

    function wpse_52414489_custom_date() {
    // Add the section to reading settings so we can add our
    // fields to it
     add_settings_section(
        'eg_custom_settings',
        'My custom settings',
        '',
        'reading'
     );
    
    // Add the field with the names and function to use for our new
    // settings, put it in our new section
     add_settings_field(
        'eg_custom_date',
        'My custom date',
        'eg_custom_date_callback',
        'reading',
        'eg_custom_settings'
     );
    
    // Register our setting so that $_POST handling is done for us and
    // our callback function just has to echo the <input>
     register_setting( 'reading', 'eg_custom_date' );
    } 
    
    function eg_custom_date_callback() {
     echo '<input name="eg_custom_date" id="eg_custom_date" type="date" value="' . get_option( 'eg_custom_date' ) . '" class="code" /> Explanation text';
    }
    
    add_action( 'admin_init', 'wpse_52414489_custom_date' );
    

    Add your shortcode (EDIT: custom date format):

    add_filter( 'init', function() {
    
     add_shortcode( 'my-custom-date', function() {
    
        return date( 'd/m/Y', strtotime( get_option( 'eg_custom_date' ) ) );
    
     });
    
    });
    

    Usage:

    [my-custom-date]
    

    Output:

    2018-09-18