wordpress搜索表单自动完成

时间:2017-07-17 00:21:42

标签: php wordpress

我正在尝试在Wordpress中添加自动完成搜索功能,我有代码但是当我开始在搜索字段中输入时自动完成不会触发,任何人都可以指导我朝正确的方向发展吗?

// PHP

$GOPATH/src/app/utils

# then import path is app/utils

// jquery

  add_action( 'init', 'casino_autocomplete_init' );
function casino_autocomplete_init() {
    // Register our jQuery UI style and our custom javascript file
    wp_enqueue_style('mycasino-jquery-ui','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css');
    wp_enqueue_script( 'my_acsearch', get_template_directory_uri() . '/js/myacsearch.js', array('jquery','jquery-ui-autocomplete'),null,true);

wp_localize_script( 'my_acsearch', 'MyAcSearch', array('url' => admin_url( 'admin-ajax.php' )));
    // Function to fire whenever search form is displayed
    add_action( 'get_search_form', 'mycasino_autocomplete_search_form' );

    // Functions to deal with the AJAX request - one for logged in users, the other for non-logged in users.
    add_action( 'wp_ajax_casino_autocompletesearch', 'mycasino_autocomplete_suggestions' );
    add_action( 'wp_ajax_nopriv_casino_autocompletesearch', 'mycasino_autocomplete_suggestions' );
}

function mycasino_autocomplete_search_form(){
    wp_enqueue_script( 'my_acsearch' );
    wp_enqueue_style( 'mycasino-jquery-ui' );
}

function mycasino_autocomplete_suggestions(){

   // custom post type
  function filter_search($query) {
  if ($query->is_search) {
  $query->set('post_type', array('custom_post', 'events'));
  };
  return $query;
  };
  add_filter('pre_get_posts', 'filter_search');


    // Query for suggestions
    $posts = get_posts( array(
        's' =>$_REQUEST['term'],
    ) );

    // Initialise suggestions array
    $suggestions=array();

    global $post;
    foreach ($posts as $post): setup_postdata($post);
        // Initialise suggestion array
        $suggestion = array();
        $suggestion['label'] = esc_html($post->post_title);
        $suggestion['link'] = get_permalink();

        // Add suggestion to suggestions array
        $suggestions[]= $suggestion;
    endforeach;

    // JSON encode and echo
    $response = $_GET["callback"] . "(" . json_encode($suggestions) . ")";
    echo $response;

    // Don't forget to exit!
    exit;
}

1 个答案:

答案 0 :(得分:1)

请确保您使用get_search_form()进行调用,而不是使用get_search_query(),您可以在创建搜索字段的主题php文件中进行检查。以上代码只能由使用get_search_form()

的主题使用