X

Data Inizio, Data Fine, Metabox per Tipi di Post Eventi Personalizzati

Snippet di IsItWP

Vuoi aggiungere tre metabox al tuo tipo di post personalizzato per eventi? Sebbene esista probabilmente un plugin per questo, abbiamo creato un rapido snippet di codice che puoi utilizzare per aggiungere metabox per data di inizio, data di fine e posizione per i tipi di post personalizzati per eventi.

Istruzioni:

Tutto quello che devi fare è aggiungere questo codice al file functions.php del tuo tema o in un plugin specifico per il sito:

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 .= "\t\t\t" . '<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;
}

Nota: Se questa è la prima volta che aggiungi snippet di codice in WordPress, consulta la nostra guida su come copiare / incollare correttamente snippet di codice in WordPress, in modo da non rompere accidentalmente il tuo sito.

Se ti è piaciuto questo snippet di codice, prendi in considerazione la lettura dei nostri altri articoli sul sito come: 15 migliori strumenti e plugin per il content marketing e Oltre 50 migliori temi WordPress responsive per creare un sito web pronto per dispositivi mobili.

Commenti   Lascia una risposta

  1. Ciao a tutti,

    questo snippet di codice è fantastico! Grazie!!

    Ma ho una domanda...
    come posso visualizzare solo il GIORNO dell'evento nella riga superiore e una riga sotto voglio visualizzare il MESE.

    grazie per il tuo supporto.
    Sven

  2. Kévin Lemonnier 17 maggio 2015 alle 11:51

    Ho migliorato questo tipo di post per creare solo _start_timestamp e _end_timestamp nel database e non giorno, mese, anno, ora e minuto.

  3. Ciao,
    Come visualizzare eventi imminenti ed eventi passati?

  4. Il codice non sembra salvare i dati della posizione. Ho controllato il DB, non ci sono e non vengono popolati nel modulo durante l'aggiornamento.

    1. soluzione:
      Aggiungi la seguente riga appena prima di questo commento: // Aggiungi i valori di $events_meta come campi personalizzati

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

      So che sono passati 2 anni, ma questo lo fa funzionare e potrebbe essere utile ad altri 😉

  5. codice di esempio su questo?

  6. Da questo codice come si visualizza un elenco di questi eventi in una singola pagina del tema?

    1. Bene, gli eventi in questo caso sarebbero un tipo di post personalizzato, o il tuo post predefinito. La visualizzazione dei tuoi eventi è la stessa di qualsiasi altro tipo di post personalizzato, ecc. Questo snippet raccoglie solo informazioni sui campi personalizzati all'interno dei seguenti valori. _day, _year, _hour, _minute e puoi visualizzarli utilizzando la funzione eventposttype_get_the_event_date in basso. Nelle righe 02, 03, 04, vedi che è collegato a un tipo di post personalizzato chiamato 'event' potresti cambiarlo in post o qualsiasi tipo di post che preferisci. Quindi visualizza semplicemente i post come al solito.

Aggiungi un commento

Siamo lieti che tu abbia scelto di lasciare un commento. Tieni presente che tutti i commenti sono moderati secondo la nostra normativa sulla privacy e tutti i link sono nofollow. NON utilizzare parole chiave nel campo del nome. Avviamo una conversazione personale e significativa.

Checklist per il lancio di WordPress

La Guida Definitiva per il Lancio di WordPress

Abbiamo raccolto tutti gli elementi essenziali della checklist per il lancio del tuo prossimo sito web WordPress in un comodo ebook.
Sì, Inviami l'eBook Gratuito!