Nội dung

ajax search cho tiêu đề website wordpress

4 năm trước, Ajax, Wordpress, 1151 Lượt xem

ở bài này netweb.vn sẽ hướng dẫn cho các bạn sợt tìm kiếm bằng ajax trong wordpess

Tích hợp live sợt cực kỳ đơn giản cho wordpress của bạn

ajax live search for post title

Html chèn vào page muốn sợt:

<!-- tim kiem post ajax-->
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="Nhập tìm kiếm post post ajax"></input>

<div id="datafetch">Kết quả trả về tìm kiếm ở đây</div>

JavaScript ( chèn vào file functions.php )

// add the ajax fetch js
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
}

 AJAX call chèn vào file functions.php

// the ajax function
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();
}

Kết quả

 

Bài viết mới cập nhập

  • Hướng dẫn Plugin floating contact

    Hướng dẫn Plugin floating contact

    10 tháng trước, 336 Lượt xem

    Netweb xin hướng dẫn cách quản lý Plugin floating contact các bạn nhớ làm theo kỹ tường bước để plugin hoạt động Tính năng: Hiển…

  • Backup Yandex Mail

    Backup Yandex Mail

    12 tháng trước, 225 Lượt xem

    Khác với dịch vụ email theo tên của microsoft và google với chi phí đắt đỏ tầm 1tr/năm/1user, vì thế nên netweb khuyên dùng dịch…

Bình luận trên facebook netweb.vn

Đam mê thiết kế web, kinh nghiệm 9 năm trong nghề thiết kế website, đang thiết kế web dạo tại netweb.vn, Callme: 08.9898.2526 (Mr Hải)