WP: кастомный поиск, передавать дополнительный параметр

259
29 октября 2017, 20:55

Задача: реализовать два поиска на одной странице, один поиск ищет в одном типе записей, другой во всех остальных, кроме первого. Использовать ajax.

После долгих чтений мануалов, вроде, смог собрать просто ajax поиск.

PHP часть

function myplugin_enqueue_scripts() {
    /* hand the js for deleting uploads by ajax */
    wp_enqueue_script('test', get_template_directory_uri() .  '/js/-test.js',   array( 'jquery' ), '1.0.0', true);
    wp_localize_script(
        'test',
        'myplugin_js', // this is the name that prefixes the ajaxurl in our js file
        array(
            'ajaxurl' => admin_url( 'admin-ajax.php' )
        )
    );
}
add_action( 'wp_enqueue_scripts', 'myplugin_enqueue_scripts' );

function myplugin_ajax_job_search() {
    /* get the search terms entered into the search box */
    $search = sanitize_text_field( $_POST[ 'search' ] );
    /* run a new query including the search string */
    $q = new WP_Query(
        array(
            'post_type'         => array( 'post', 'analizy' ),
            'posts_per_page'    => 8,
            's'                 => $search
        )
    );
    /* store all returned output in here */
    $output = '';
    /* check whether any search results are found */
    if( $q->have_posts() ) {
        /* loop through each result */
        while( $q->have_posts() ) : $q->the_post();
            /* add result and link to post to output */
            echo '<a class="ajax-result-item" href="' . get_permalink() . '">' . get_the_title() . '</a>';
        /* end loop */
        endwhile;
    /* no search results found */   
    } else {
        /* add no results message to output */
        echo 'error';
    } // end if have posts
    /* reset query */
    wp_reset_query();
    die();
}

add_action( 'wp_ajax_myplugin_ajax_search_jobs', 'myplugin_ajax_job_search' );
add_action( 'wp_ajax_nopriv_myplugin_ajax_search_jobs', 'myplugin_ajax_job_search' );

JS

var searchRequest = null;
$(function () {
    var minlength = 3;
    $(".ajax-search").keyup(function () {
        var that = this,
        value = $(this).val();
        if (value.length >= minlength ) 
        {
            if (searchRequest != null) 
                searchRequest.abort();
            searchRequest = $.ajax({
                type: 'post',
                url: myplugin_js.ajaxurl, // the localized name of your file
                data: {
                    action: 'myplugin_ajax_search_jobs', // the wp_ajax_ hook name
                    search: value
                },
                beforeSend: function() {
                    $('#lol').show();
                },
                success: function( result ){
                    //we need to check if the value is the same
                    if (value==$(that).val()) {
                    //Receiving the result of search here
                        if( result === 'error' ) {
                            // set the html of the element with the class to no results
                            $( '.ajax-results-list' ).html( 'Ничего не найдено' );
                        // we have results to display
                        } else {
                            // populate the results markup in the element with the class of ajax-results
                            $( '.ajax-results-list' ).html( result );
                        }   
                        $('#lol').hide();
                    }
                }
            });
        }
    });
});

HTML

<form role="search" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
                                        <input type="text" class="ajax-search" name="s" placeholder="Поиск..." id="search-area" value="<?php the_search_query(); ?>" /><input value="" id="search-button" class="" type="submit">
                                    </form>

Проблема: Почему-то поиск реагирует на все кнопки (стрелки, F1-F12 и т.д.), хотя по идее не должен. Где ошибка?

Задача: Форм поиска на странице будет две. Хочу добавить в формы скрытый input с параметром. И чтобы получении запроса на сервер срабатывало условие что-то типа Если параметр равен = значени1, то в аргументы цикла подставлять один post_type Если параметр равен = значение2, то другие post_type.

Условие построить могу, не могу отправить инфу на сервер и обработать её.

READ ALSO
Joomla 3. Анонсы со ссылками на категорию

Joomla 3. Анонсы со ссылками на категорию

На главной странице у меня небольшой блок, в котором 7 пунктов слева, и справа краткое описание каждого материала с кнопкой "подробнее", через...

277
Токен в ВК для обработки на сервере

Токен в ВК для обработки на сервере

Хочу написать скрипт, который на сайте работает с сообщениями в ВК, выводит сообщения там, составляет статистикуНо проблема в том, что я никак...

311
Android -&gt; PHP подключение

Android -> PHP подключение

Так выглядит мой текущий кодСуть в том, что при отладке не происходит ошибок, а PHP файл должен принимать корректно

249
Как работает компонент Console в Symfony 3?

Как работает компонент Console в Symfony 3?

Пример класса некой команды:

226