WordPress Ajax搜索
都说WordPress的搜索功能很占服务器资源,不知道Ajax方式也不会不会这样,具体我也没有去测试过。今天就给大家分享一下WordPress Ajax搜索,效果图如上!
add_action( 'wp_ajax_nopriv_ajax_search', array( $this, 'ajax_search' ) ); add_action( 'wp_ajax_ajax_search', array( $this, 'ajax_search' ) );
public function ajax_search() { if ( isset( $_REQUEST['fn'] ) && 'get_ajax_search' == $_REQUEST['fn'] ) { $search_query = new WP_Query( array( 's' => $_REQUEST['terms'], 'posts_per_page' => 10, 'no_found_rows' => true, ) ); $results = array( ); if ( $search_query->get_posts() ) { foreach ( $search_query->get_posts() as $the_post ) { $title = get_the_title( $the_post->ID ); $results[] = array( 'value' => $title, 'url' => get_permalink( $the_post->ID ), 'tokens' => explode( ' ', $title ), ); } } else { $results[] = '对不起的,没有结果匹配到你的关键词'; } wp_reset_postdata(); echo json_encode( $results ); } die(); }
功能函数大概就是这样,再配合上JS即可获取数据(具体文件文章结尾处下载)。使用方法也很简单,调用WordPress默认的搜索框即可!
get_search_form()
[buttons text=”下载地址” url=”https://drive.google.com/open?id=0B4ytzsRNIg7geVFsTlg5UkZBaDQ” icons=”icon-xiazai” color=”danger” border=”no” target=”yes” ]