WordPress Ajax Search

    之前出了一篇AJAX搜索的文章,但是我总觉得需要加载的文件太多,不怎么实用。今天抽空就做一篇简单的Ajax Search 搜索,先声明一下,此教程并非我原创。

    [insert_post ids=1396]

    [insert_post ids=1148]

    Wordpress Ajax Search

    首先呢我们创建一个搜索input,具体代码是这样的:

    <input type="text" name="keyword" id="keyword" onkeyup="fetch()">
    
    <div id="datafetch">这里显示搜索结果</div>

    然后准备相关JS,这儿有两种方法载入,第一直接在functions.php中添加代码:

    add_action( 'wp_footer', 'ajax_fetch' );
    function ajax_fetch() {
    ?>
    <script type="text/javascript">
    function fetch(){
    
        jQuery.ajax({
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            type: 'post',
            data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
            success: function(data) {
                jQuery('#datafetch').html( data );
            }
        });
    
    }
    </script>
    
    <?php
    }

    或者你也可以使用Wordpress标准载入JS文件的方式加载。最后我们要在functions.php中添加构造Ajax Search的功能函数

    add_action('wp_ajax_data_fetch' , 'data_fetch');
    add_action('wp_ajax_nopriv_data_fetch','data_fetch');
    function data_fetch(){
    
        $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
        if( $the_query->have_posts() ) :
            while( $the_query->have_posts() ): $the_query->the_post(); ?>
    
                <h2><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h2>
    
            <?php endwhile;
            wp_reset_postdata();  
        endif;
    
        die();
    }

    如果你照着此教程操作,此时的文本框填入关键词就能搜索出站点文章,不过关于搜索结果的显示则需要自己去写样式。

    如果你有任何疑问可以留言咨询。

    Responses

    您的电子邮箱地址不会被公开。 必填项已用*标注

    Up Next:

    Ajax登陆注册找回密码插件更新至V1.3

    Ajax登陆注册找回密码插件更新至V1.3