Объединение входных данных даты и времени в одно поле с метабоксами WPAlchemy - PullRequest
0 голосов
/ 26 марта 2011

Я пытаюсь преобразовать метабокс для даты и времени, которое я сейчас использую, в метабокс WPAlchemy.

В настоящее время я объединяю дату начала и время начала в одно поле после сохранения.

Это старая функция сохранения:

add_action ('save_post', 'save_event');

function save_event(){

    global $post;

    // - still require nonce

    if ( !wp_verify_nonce( $_POST['event-nonce'], 'event-nonce' )) {
        return $post->ID;
    }

    if ( !current_user_can( 'edit_post', $post->ID ))
        return $post->ID;

    // - convert back to unix & update post

    if(!isset($_POST["startdate"])):
        return $post;
        endif;
        $updatestartd = strtotime ( $_POST["startdate"] . $_POST["starttime"] );
        update_post_meta($post->ID, "startdate", $updatestartd );

    if(!isset($_POST["enddate"])):
        return $post;
        endif;
        $updateendd = strtotime ( $_POST["enddate"] . $_POST["endtime"]);
        update_post_meta($post->ID, "enddate", $updateendd );

Вот новые функции и поля для справки:

$custom_event_metabox = new WPAlchemy_MetaBox(array
(
    'id' => '_custom_event_meta',
    'title' => 'Event Information',
    'template' => /event_meta.php',
    'types' => array('event'),
    'context' => 'normal',
    'priority' => 'high',
    'mode' => WPALCHEMY_MODE_EXTRACT,
    'save_filter' => 'event_save_filter',
    'prefix' => '_my_' // defaults to NULL
));

            <li><label>Start Date</label>
            <?php $mb->the_field('startdate'); ?>
            <input type="text" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>" class="tsadate" />
            </li>

            <li><label>Start Time</label>
            <?php $mb->the_field('starttime'); ?>
            <input type="text" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>" class="tsatime" />
            <span><em>Use 24h format (7pm = 19:00)</em></span>
            </li>

            <li><label>End Date</label>
            <?php $mb->the_field('enddate'); ?>
            <input type="text" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>" class="tsadate" />
            </li>

            <li><label>End Time</label>
            <?php $mb->the_field('endtime'); ?>
            <input type="text" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>" class="tsatime" />
            <span><em>Use 24h format (7pm = 19:00)</em></span>

Проблема, с которой я столкнулсяЯ не совсем уверен, должен ли я использовать save_filter или save_action, или как я должен справиться с этим, используя ala WPAlchemy.

Это то, что у меня есть до сих пор:* if (! isset ($ _ POST ["enddate"])): return $ post;ENDIF;$ updateendd = strtotime ($ _POST ["enddate"]. $ _POST ["endtime"]);update_post_meta ($ post-> ID, "enddate", $ updateendd);

    // filters must always continue the chain and return the data (passing it through the filter)
    return $meta;

}

Будет ли это работать?И должен ли это быть save_filter или save_action?

Любое понимание приветствуется; -)

1 Ответ

2 голосов
/ 26 марта 2011

Если вы используете WPAlchemy, и все, что вам нужно, это добавить новые значения или обновить значения в ваших метаданных. Вы можете добиться этого, добавив дополнительные значения в массив $meta. Когда вы возвращаете его, как всегда, когда используете save_filter, WPAlchemy будет обрабатывать сохранение данных.

Основное различие между save_filter против save_action состоит в том, что с фильтром вы должны передать обратно значение $meta, но перед этим вы можете изменить массив, что позволит вам сохранить скрытые значения.

Преимущество использования любого из этих параметров заключается в том, что вы можете манипулировать другими аспектами WordPress во время пост-обновления и в соответствии со значениями, которые вводит пользователь.

Передача назад false в save_filter заставляет WPAlchemy остановиться и не сохранять. Дополнительное различие между ними заключается также в том, что save_filter происходит до сохранения, а save_action происходит после.

Вот моя попытка настроить ваш код выше, очевидно, вам придется подправить его, чтобы он работал для вас, пожалуйста, прочитайте комментарии, которые я включил.

function event_save_filter($meta, $post_id)
{
    // the meta array which can be minipulated
    var_dump($meta);

    // the current post id
    var_dump($post_id);

    // fix: remove exit, exit here only to show you the output when saving
    //exit;


    // at this time WPAlchemy does not have any field validation
    // it is best to handle validation with JS prior to form submit
    // If you are going to handle validation here, then you should
    // probably handle it up front before saving anything

    if( ! isset($meta['startdate']) OR ! isset($meta['enddate']))
    {
        // returning false stops WPAlchemy from saving
        return false;
    }

    $updatestartd = strtotime($meta['startdate'] . $meta['starttime']);

    // this is an example of setting an additional meta value
    $meta['startdate_ts'] = $updatestartd;

    // important:
    // you may or may not need the following, at this time, 
    // WPAlchemy saves its data as an array in wp_postmeta,
    // this is good or bad depending on the task at hand, if
    // you need to use query_post() WP function with the "startdate"
    // parameter, your best bet is to set the following meta value
    // outside of the WPAlchemy context.

    update_post_meta($post_id, "startdate", $updatestartd );

    $updateendd = strtotime ($meta['enddate'] . $meta['endtime']); 

    // similar note applies
    update_post_meta($post_id, "enddate", $updateendd );

    // filters must always continue the chain and return the data (passing it through the filter)
    return $meta;

}
...