Запрос бронирования WooCommerce по дате доступности

Я использую бронирование Woothemes для своего сайта woocommerce.

Поскольку я создаю пользовательский поиск продуктов, мне также нужно искать доступность, вот как я должен управлять доступностью от B.O Booking  plugin B.O и как плагин сохраняет в базу данных

a:8:{i:0;a:4:{s:4:"type";s:4:"days";s:8:"bookable";s:3:"yes";s:4:"from";s:1:"3";s:2:"to";s:1:"3";}i:1;a:4:{s:4:"type";s:6:"custom";s:8:"bookable";s:3:"yes";s:4:"from";s:10:"2015-07-09";s:2:"to";s:10:"2015-07-09";}i:2;a:4:{s:4:"type";s:6:"custom";s:8:"bookable";s:3:"yes";s:4:"from";s:10:"2015-07-08";s:2:"to";s:10:"2015-07-08";}i:3;a:4:{s:4:"type";s:6:"custom";s:8:"bookable";s:3:"yes";s:4:"from";s:10:"2015-07-10";s:2:"to";s:10:"2015-07-10";}i:4;a:4:{s:4:"type";s:6:"custom";s:8:"bookable";s:3:"yes";s:4:"from";s:10:"2015-07-15";s:2:"to";s:10:"2015-07-15";}i:5;a:4:{s:4:"type";s:6:"custom";s:8:"bookable";s:3:"yes";s:4:"from";s:10:"2015-07-16";s:2:"to";s:10:"2015-07-16";}i:6;a:4:{s:4:"type";s:6:"custom";s:8:"bookable";s:3:"yes";s:4:"from";s:10:"2015-07-17";s:2:"to";s:10:"2015-07-17";}i:7;a:4:{s:4:"type";s:6:"months";s:8:"bookable";s:2:"no";s:4:"from";s:1:"8";s:2:"to";s:1:"8";}}

Я могу получить эти значения из встроенной функции wordpress get_post_meta,

$avail = get_post_meta($product->id, '_wc_booking_availability');

и результат:

Array
(
[0] => Array
    (
        [type] => days
        [bookable] => yes
        [from] => 3
        [to] => 3
    )

[1] => Array
    (
        [type] => custom
        [bookable] => yes
        [from] => 2015-07-09
        [to] => 2015-07-09
    )

[2] => Array
    (
        [type] => custom
        [bookable] => yes
        [from] => 2015-07-08
        [to] => 2015-07-08
    )

[3] => Array
    (
        [type] => custom
        [bookable] => yes
        [from] => 2015-07-10
        [to] => 2015-07-10
    )

[4] => Array
    (
        [type] => custom
        [bookable] => yes
        [from] => 2015-07-15
        [to] => 2015-07-15
    )

[5] => Array
    (
        [type] => custom
        [bookable] => yes
        [from] => 2015-07-16
        [to] => 2015-07-16
    )

[6] => Array
    (
        [type] => custom
        [bookable] => yes
        [from] => 2015-07-17
        [to] => 2015-07-17
    )

[7] => Array
    (
        [type] => months
        [bookable] => no
        [from] => 8
        [to] => 8
    )

)

Как вы можете видеть, пользователь может указать, доступен ли продукт для бронирования или нет в диапазоне дней или месяцев, поэтому мой вопрос заключается в том, как я могу выполнить sql-запрос, чтобы проверить, доступна ли переменная даты для этого продукта, я думаю, что meta_query сделает задание (как показано ниже), но как я могу указать недоступную дату? Как ты думаешь?

if($_GET['when']){

        /* checkIsAValidDate() >> check date format */
        if ( checkIsAValidDate( $_GET['when'] ) ){
            $quand = $_GET['when'];
            $available = array(
                "post_type" => "product",
                "meta_query" => array(
                    "relation"  => "AND",
                    "key"       => '_wc_booking_availability',
                    "value"     => $when,
                    'compare'   => 'IN'
                )
            );

        }
    }

person Community    schedule 08.06.2015    source источник


Ответы (1)


Поскольку мета-значение представляет собой массив, может оказаться невозможным используйте WP_Meta_Query. Хотя я согласен с тем, что использование WP_Meta_Query кажется более элегантным способом сделать это, я всегда находил эту функцию действительно запутанной, и, поскольку вы можете получить массив резервируемых объектов, кажется, что было бы просто написать такую ​​функцию:

/**
 * Returns an array of bookable products according to supplied criteria
 * 
 * @param  int    $pid      the $product->ID of the bookable object
 * @param  mixed  $when     a date in YYYY-MM-DD format or integer representing a day or month
 * @param  string $type     a value of 'day', 'month', or 'custom'
 * @param  string $bookable whether the bookable object is bookable or not ('yes' or 'no')
 * @return array            an array of bookable objects for the product
 */
function getBookables( $pid, $when, $type, $bookable = 'yes' ) {
    $result = array();

    // is $when in the YYYY-MM-DD format?
    if ( 'custom' == $type ) {
        // it's a custom date so convert $when to DateTime
        $when = DateTime::createFromFormat( 'Y-m-d', $when );
    }

    $availability = get_post_meta( $pid, '_wc_booking_availability' );
    foreach ( $availability as $a ) {
        if ( $a[ 'bookable' ] == $bookable ) {
            // is it in the YYYY-MM-DD format?
            if ( $when instanceof DateTime ) {
                // it's a custom date so use date compare
                $from = DateTime::createFromFormat( 'Y-m-d', $a[ 'from' ] );
                $to   = DateTime::createFromFormat( 'Y-m-d', $a[ 'to'   ] );
                if ( $when >= $from && $when <= $to ) {
                    $result[] = $a;
                }
            } else {
                // it is an integer value (day or month)
                if ( $type == $a[ 'type' ] && ( $when >= $from && $when <= $to ) ) {
                    $result[] = $a;
                }
            }
        }
    }
    return $result;
}

Обратите внимание, что, вероятно, необходимо передать type функции поиска, поскольку, хотя я могу отличить значения YYYY-MM-DD от значений int, нет простого способа отличить значения month от значений day. Таким образом, вы можете использовать вышеуказанную функцию:

if ( $_GET[ 'when' ] && $_GET[ 'type' ] ) {
    $when = $_GET[ 'when' ];
    $type = $_GET[ 'type' ];
    $bookables = getBookables( $product->ID, $when, $type );
}

Также обратите внимание, что если вы передадите строку 'no' в качестве четвертого параметра функции, вы можете получить список недоступного времени.

Надеюсь это поможет!

person morphatic    schedule 18.09.2015