X

Date de début, date de fin, métaboxe pour les types d’articles personnalisés sur les événements

Snippets by IsItWP

Voulez-vous ajouter trois métaboxes à vos types de posts personnalisés pour les événements ? Bien qu’il existe probablement un plugin pour cela, nous avons créé un extrait de code rapide que vous pouvez utiliser pour ajouter la date de début, la date de fin et la métaboxe de lieu pour les types de posts personnalisés d’événements.

Instructions:

Tout ce que vous avez à faire est d’ajouter ce code au fichier functions.php de votre thème ou dans un plugin spécifique à votre site:

function ep_eventposts_metaboxes() {
    add_meta_box( 'ept_event_date_start', 'Start Date and Time', 'ept_event_date', 'event', 'side', 'default', array( 'id' => '_start') );
    add_meta_box( 'ept_event_date_end', 'End Date and Time', 'ept_event_date', 'event', 'side', 'default', array('id'=>'_end') );
    add_meta_box( 'ept_event_location', 'Event Location', 'ept_event_location', 'event', 'side', 'default', array('id'=>'_end') );
}
add_action( 'admin_init', 'ep_eventposts_metaboxes' );
 
// Metabox HTML
 
function ept_event_date($post, $args) {
    $metabox_id = $args['args']['id'];
    global $post, $wp_locale;
 
    // Use nonce for verification
    wp_nonce_field( plugin_basename( __FILE__ ), 'ep_eventposts_nonce' );
 
    $time_adj = current_time( 'timestamp' );
    $month = get_post_meta( $post->ID, $metabox_id . '_month', true );
 
    if ( empty( $month ) ) {
        $month = gmdate( 'm', $time_adj );
    }
 
    $day = get_post_meta( $post->ID, $metabox_id . '_day', true );
 
    if ( empty( $day ) ) {
        $day = gmdate( 'd', $time_adj );
    }
 
    $year = get_post_meta( $post->ID, $metabox_id . '_year', true );
 
    if ( empty( $year ) ) {
        $year = gmdate( 'Y', $time_adj );
    }
 
    $hour = get_post_meta($post->ID, $metabox_id . '_hour', true);
 
    if ( empty($hour) ) {
        $hour = gmdate( 'H', $time_adj );
    }
 
    $min = get_post_meta($post->ID, $metabox_id . '_minute', true);
 
    if ( empty($min) ) {
        $min = '00';
    }
 
    $month_s = '<select name="' . $metabox_id . '_month">';
    for ( $i = 1; $i < 13; $i = $i +1 ) {
        $month_s .= "ttt" . '<option value="' . zeroise( $i, 2 ) . '"';
        if ( $i == $month )
            $month_s .= ' selected="selected"';
        $month_s .= '>' . $wp_locale->get_month_abbrev( $wp_locale->get_month( $i ) ) . "</option>n";
    }
    $month_s .= '</select>';
 
    echo $month_s;
    echo '<input type="text" name="' . $metabox_id . '_day" value="' . $day  . '" size="2" maxlength="2" />';
    echo '<input type="text" name="' . $metabox_id . '_year" value="' . $year . '" size="4" maxlength="4" /> @ ';
    echo '<input type="text" name="' . $metabox_id . '_hour" value="' . $hour . '" size="2" maxlength="2"/>:';
    echo '<input type="text" name="' . $metabox_id . '_minute" value="' . $min . '" size="2" maxlength="2" />';
 
}
 
function ept_event_location() {
    global $post;
    // Use nonce for verification
    wp_nonce_field( plugin_basename( __FILE__ ), 'ep_eventposts_nonce' );
    // The metabox HTML
    $event_location = get_post_meta( $post->ID, '_event_location', true );
    echo '<label for="_event_location">Location:</label>';
    echo '<input type="text" name="_event_location" value="' . $event_location  . '" />';
}
 
// Save the Metabox Data
 
function ep_eventposts_save_meta( $post_id, $post ) {
 
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return;
 
    if ( !isset( $_POST['ep_eventposts_nonce'] ) )
        return;
 
    if ( !wp_verify_nonce( $_POST['ep_eventposts_nonce'], plugin_basename( __FILE__ ) ) )
        return;
 
    // Is the user allowed to edit the post or page?
    if ( !current_user_can( 'edit_post', $post->ID ) )
        return;
 
    // OK, we're authenticated: we need to find and save the data
    // We'll put it into an array to make it easier to loop though
 
    $metabox_ids = array( '_start', '_end' );
 
    foreach ($metabox_ids as $key ) {
        $events_meta[$key . '_month'] = $_POST[$key . '_month'];
        $events_meta[$key . '_day'] = $_POST[$key . '_day'];
            if($_POST[$key . '_hour']<10){
                 $events_meta[$key . '_hour'] = '0'.$_POST[$key . '_hour'];
             } else {
                   $events_meta[$key . '_hour'] = $_POST[$key . '_hour'];
             }
        $events_meta[$key . '_year'] = $_POST[$key . '_year'];
        $events_meta[$key . '_hour'] = $_POST[$key . '_hour'];
        $events_meta[$key . '_minute'] = $_POST[$key . '_minute'];
        $events_meta[$key . '_eventtimestamp'] = $events_meta[$key . '_year'] . $events_meta[$key . '_month'] . $events_meta[$key . '_day'] . $events_meta[$key . '_hour'] . $events_meta[$key . '_minute'];
    }
 
    // Add values of $events_meta as custom fields
 
    foreach ( $events_meta as $key => $value ) { // Cycle through the $events_meta array!
        if ( $post->post_type == 'revision' ) return; // Don't store custom data twice
        $value = implode( ',', (array)$value ); // If $value is an array, make it a CSV (unlikely)
        if ( get_post_meta( $post->ID, $key, FALSE ) ) { // If the custom field already has a value
            update_post_meta( $post->ID, $key, $value );
        } else { // If the custom field doesn't have a value
            add_post_meta( $post->ID, $key, $value );
        }
        if ( !$value ) delete_post_meta( $post->ID, $key ); // Delete if blank
    }
 
}
 
add_action( 'save_post', 'ep_eventposts_save_meta', 1, 2 );
 
/**
 * Helpers to display the date on the front end
 */
 
// Get the Month Abbreviation
 
function eventposttype_get_the_month_abbr($month) {
    global $wp_locale;
    for ( $i = 1; $i < 13; $i = $i +1 ) {
                if ( $i == $month )
                    $monthabbr = $wp_locale->get_month_abbrev( $wp_locale->get_month( $i ) );
                }
    return $monthabbr;
}
 
// Display the date
 
function eventposttype_get_the_event_date() {
    global $post;
    $eventdate = '';
    $month = get_post_meta($post->ID, '_month', true);
    $eventdate = eventposttype_get_the_month_abbr($month);
    $eventdate .= ' ' . get_post_meta($post->ID, '_day', true) . ',';
    $eventdate .= ' ' . get_post_meta($post->ID, '_year', true);
    $eventdate .= ' at ' . get_post_meta($post->ID, '_hour', true);
    $eventdate .= ':' . get_post_meta($post->ID, '_minute', true);
    echo $eventdate;
}

Note : Si c’est la première fois que vous ajoutez des extraits de code dans WordPress, veuillez vous référer à notre guide sur comment copier/coller correctement des extraits de code dans WordPress, afin de ne pas casser accidentellement votre site.

Si vous avez aimé cet extrait de code, n’hésitez pas à consulter nos autres articles sur le site comme : 15 meilleurs outils et plugins de marketing de contenu et 50+ meilleurs thèmes WordPress responsive pour créer un site web prêt pour le mobile.

Commentaires   laisser une réponse

  1. Hello all,

    this code snippet is great! Thanks!!

    But i have a question…
    how can i display only the event DAY in the top row and one row below i want to display the MONTH.

    thx for your Support.
    Sven

  2. Kévin Lemonnier mai 17, 2015 à 11:51 am

    I improved this post type to create only _start_timestamp and _end_timestamp in the database and not day, month, year, minute and hour.

  3. Hi,
    How to display upcoming events and past events ?

  4. The code does not seem to be saving the Location data. Checked the DB, it’s not there and it’s not getting populated in the form upon updating.

    1. solution:
      add the following line just before this comment: // Add values of $events_meta as custom fields

      $events_meta[‘_event_location’] = $_POST[‘_event_location’];

      I know it has been 2 years, but this makes it work and others might find it helpful 😉

  5. sample code on this one?

  6. From this code how do you display a list of these events in a single theme page?

    1. Well the events in this case would be a custom post type, or your default post. Displaying your events is the same as any other custom post type etc. This snippet just collects custom field information within the following values. _day, _year, _hour, _minute and you can display them using the eventposttype_get_the_event_date function at the bottom. On lines 02, 03, 04, you see that it is attached to a custom post type called ‘event’ you could change that to post or whatever post type you like. Then just display posts as normal.

Ajouter un commentaire

Nous sommes heureux que vous ayez choisi de laisser un commentaire. N'oubliez pas que tous les commentaires sont modérés conformément à notre privacy policy, et que tous les liens sont en nofollow. N'utilisez PAS de mots-clés dans le champ du nom. Engageons une conversation personnelle et constructive.

WordPress Launch Checklist

L'ultime liste de contrôle pour le lancement de WordPress

Nous avons rassemblé tous les éléments essentiels de la liste de contrôle pour le lancement de votre prochain site Web WordPress dans un ebook pratique.
Oui, envoyez-moi le gratuit !