Home > Software engineering >  Get start date of event, format it and then display it with a shortcode
Get start date of event, format it and then display it with a shortcode

Time:05-16

I have an [essential grid] grid which goes through some [the events calendar] events. Now in each of those items, I want to display the event start date but when I use the relevant meta key as a parameter source in the grid item, I get the default date format back. Thing is I need to format that date in a specific way and what I stumbled upon is this solution:

function tribe_start_date_shortcode() {
    global $post;
    return tribe_get_start_date( $post->ID, false, 'F j, Y' );
}

add_shortcode('tribe-start-date', 'tribe_start_date_shortcode');

Now, the date does indeed get formatted just fine when I use the shortcode where I need it but the problem is that instead of the event start date, what I get back is the current WordPress post date (ie where the grid is running).

How can I get it to show the event item's date instead?

Any help would be greatly appreciated, thanks!

---------------------------//---------------------------

Working code (thanks to @Howard E):

// Get post id through the shortcode and return formatted date
function tribe_start_date_shortcode( $atts ) {
    $atts = shortcode_atts(array('event' => ''), $atts, 'tribe-start-date');
    return tribe_get_start_date( absint( $atts['event'] ), false, 'F j, Y' );
}

// Wordpress shortcode register
add_shortcode('tribe-start-date', 'tribe_start_date_shortcode');

// Place the above in your theme's functions.php

// Actual shortcode to be placed within the Essential Grid Item Skin relevant layer
[tribe-start-date event=%post_id%]

CodePudding user response:

You could pass the event ID through to the shortcode. The global $post will not retrieve the post object whilst inside a shortcode function.

Use the shortcode like this

[tribe-start-date event=123]

function tribe_start_date_shortcode( $atts ) {
    $atts = shortcode_atts(
        array(
            'event' => '',
        ),
        $atts,
        'tribe-start-date',
    );
    return tribe_get_start_date( absint( $atts['event'] ), false, 'F j, Y' );
}
add_shortcode( 'tribe-start-date', 'tribe_start_date_shortcode' );
  • Related