Фильтр для пользовательского типа записи (ACF) не работает - PullRequest
0 голосов
/ 07 апреля 2020

Я создаю веб-сайт для компании по продаже подержанных автомобилей, я создал собственный тип постов, называемый «случаю», у каждого автомобиля есть пара настраиваемых полей, например, make, model et c.

Теперь я хочу иметь возможность фильтровать обзор автомобиля по марке модели.

Я использую пример, приведенный ACF: https://www.advancedcustomfields.com/resources/creating-wp-archive-custom-field-filter/

Но я не могу заставить его работать. Значения полей ввода установлены, но я получаю ошибку при перенаправлении. Понятия не имею почему. скриншот страницы ошибки и URL

Может кто-нибудь мне помочь?

функция. php:

/**
 * Custom car filter
 */
// array of filters (field key => field name)
$GLOBALS['my_query_filters'] = array( 
    'field_1'   => 'make', 
    'field_2'   => 'model',
    'field_3'   => 'price',
    'field_4'   => 'production_year',
    'field_5'   => 'mileage'
);


// action
add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);

function my_pre_get_posts( $query ) {

    // bail early if is in admin
    if( is_admin() ) return;

    // bail early if not main query
    // - allows custom code / plugins to continue working
    if( !$query->is_main_query() ) return;

    // get meta query
    $meta_query = $query->get('meta_query');

    // loop over filters
    foreach( $GLOBALS['my_query_filters'] as $key => $name ) {

        // continue if not found in url
        if( empty($_GET[ $name ]) ) {
            continue;
        }

        // get the value for this filter
        // eg: http://www.website.com/events?city=melbourne,sydney
        $value = explode(',', $_GET[ $name ]);

        // append meta query
        $meta_query[] = array(
            'key'       => $name,
            'value'     => $value,
            'compare'   => 'IN',
        );
    }

    // update meta query
    $query->set('meta_query', $meta_query);

}

фильтр:

<div id="cars-filters" class="car-filter">
    <form>
        <?php foreach( $GLOBALS['my_query_filters'] as $key => $name ): 

            // get the field's settings without attempting to load a value
            $field = get_field_object($key, false, false);


            // set value if available
            if( isset($_GET[ $name ]) ) {

                $field['value'] = explode(',', $_GET[ $name ]);

            }

            // create filter
            ?>
            <label>
                <h3><?php echo $name; ?></h3>
                <div class="filter" data-filter="<?php echo $name; ?>">
                    <?php create_field( $field ); ?>
                </div>
            </label>

        <?php endforeach; ?>
        <label>
            <input type="submit" value="Zoeken">
        </label>
    </form>
    </div>

    <script type="text/javascript">
    (function($) {

        $.fn.enterKey = function (fnc) {
            return this.each(function () {
                $(this).keypress(function (ev) {
                    var keycode = (ev.keyCode ? ev.keyCode : ev.which);
                    if (keycode == '13') {
                        fnc.call(this, ev);
                    }
                })
            })
        }

        // change
        // $('#cars-filters').on('change', 'input[type="text"]', function(e){
        $('#cars-filters').on('click enterKey', 'input[type="submit"]', function(e){
                e.preventDefault()

            // vars
            var url = '<?php echo home_url('occasions'); ?>';
                args = {};


            // loop over filters
            $('#cars-filters .filter').each(function(){

                // vars
                var filter = $(this).data('filter'),
                    vals = [];


                // find checked inputs
                $(this).find('input[type="text"]').each(function(){

                    vals.push( $(this).val() );

                });


                // append to args
                args[ filter ] = vals.join(',');

            });


            // update url
            url += '?';


            // loop over args
            $.each(args, function( name, value ){

                url += name + '=' + value + '&';

            });


            // remove last &
            url = url.slice(0, -1);


            // reload page
            window.location.replace( url );


        });

    })(jQuery);
    </script>
...