búsqueda en vivo ajax para títulos de entradas

22 sept 2016, 01:18:54
Vistas: 48.7K
Votos: 5

Estoy creando una búsqueda en vivo con AJAX para filtrar títulos de entradas en mi tema de WordPress. Cuando escribo algo en el input muestra todas las entradas en el resultado, sin filtrar para obtener entradas personalizadas.

¿Cómo realizar una búsqueda en vivo y encontrar una entrada con AJAX?

Function.php

<?php 
add_action('wp_ajax_my_action' , 'data_fetch');
add_action('wp_ajax_nopriv_my_action','data_fetch');

function data_fetch(){
    $the_query = new WP_Query(array('post_per_page'=>5));
    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();
}?>

Script:

<script>
function fetch(){

    $.post('<?php echo admin_url('admin-ajax.php'); ?>',{'action':'my_action'},
    function(response){
        $('#datafetch').append(response);
        console.log(result);
    });
}
</script>

HTML:

<input type="text" onkeyup="fetch()"></input>
    <div id="datafetch">
</div>
2
Comentarios

¿Entonces quieres que la consulta busque dentro de los títulos de las publicaciones (y la palabra clave del título se pasa a través del campo de entrada en tu formulario HTML)?

Ahmed Fouad Ahmed Fouad
22 sept 2016 01:21:39

@AhmedElmahdy SÍ

FRQ6692 FRQ6692
22 sept 2016 01:23:10
Todas las respuestas a la pregunta 4
4
22

Aquí hay una solución funcional (probada tal cual)

El HTML (podría ser parte del contenido de la página)

<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>

<div id="datafetch">Los resultados de búsqueda aparecerán aquí</div>

El JavaScript (va al functions.php de tu tema)

// añade el js de fetch ajax
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
}

Y finalmente la llamada AJAX va al functions.php de tu tema

// la función ajax
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( get_permalink() ); ?>"><?php the_title();?></a></h2>

        <?php endwhile;
        wp_reset_postdata();  
    endif;

    die();
}

Adicional: Así es como hice que mi función AJAX busque de manera precisa:

// la función ajax
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();

$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {?>
            <h4><a href="<?php echo esc_url( get_permalink() ); ?>"><?php the_title();?></a></h4>
        <?php
                                  }
    endwhile;
        wp_reset_postdata();  
    endif;

    die();
}
22 sept 2016 01:46:05
Comentarios

¿Conoces alguna forma de buscar la palabra clave solo en el título o solo en la descripción?

Fanky Fanky
13 feb 2020 20:06:19

quizás solo usando el filtro posts_where en lugar de 's' como en https://wordpress.stackexchange.com/questions/298888/wp-query-where-title-begins-with-a-specific-letter)

Fanky Fanky
13 feb 2020 20:17:51

Necesito que las publicaciones estén presentes en lugar del texto "los resultados de búsqueda aparecerán aquí", luego cuando ocurre la búsqueda, simplemente filtra los resultados. ¿Es posible esto con este método? Actualmente lo tengo implementado y funciona, pero tengo una página en blanco antes de que ocurra la búsqueda

Amir Khadem Amir Khadem
14 jul 2021 03:03:37

Respuesta excelente. Solo reemplacé post_permalink() (obsoleto) por get_permalink()

User User
12 ene 2022 04:09:27
0

Olvidaste llamarlo como searchinput, puedes pegar el siguiente código en functions.php

// la función ajax
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' => 5, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
    if( $the_query->have_posts() ) :
        while( $the_query->have_posts() ): $the_query->the_post(); ?>

            <a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a>

        <?php endwhile;
        wp_reset_postdata();  
    else: 
        echo '<h3>No se encontraron resultados</h3>';
    endif;
        die();
    }

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

    }
    </script>

    <?php
    }

Una vez hecho esto, busca y abre searchform.php. Ahora lo que tienes que hacer es reemplazar el elemento id con el elemento id anterior (searchInput) y agregar este código

onkeyup="fetchResults()"

Junto al elemento id, por lo que el código general quedará así

    <form method="get" class="td-search-form-widget" action="<?php echo esc_url(home_url( '/' )); ?>">
    <div role="search">
        <input class="td-widget-search-input" type="text" value="<?php echo get_search_query(); ?>" name="s" id="searchInput" onkeyup="fetchResults()" /><input class="wpb_button wpb_btn-inverse btn" type="submit" id="searchsubmit" value="<?php _etd('Buscar', TD_THEME_NAME)?>" />
    </div>
</form>

Asegúrate de hacer los cambios en el tema hijo. Ahora el último paso: agrega <div id="datafetch"></div> justo encima del formulario y podrás ver la búsqueda en vivo en tu formulario de búsqueda.

También puedes hacer esto mediante un plugin de búsqueda en vivo, la forma más fácil de hacerlo si no sabes cómo codificar. Espero que te ayude.

7 oct 2019 08:48:44
0
/* Campos rellenados en el perfil de administrador */
add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );
function extra_user_profile_fields( $user ) { ?>
    <h3><?php _e("Información adicional del perfil", "blank"); ?></h3>

    <table class="form-table">
    <tr>
        <th><label for="address"><?php _e("Dirección"); ?></label></th>
        <td>
            <input type="text" name="postSearch" id="postSearch" value="<?php echo esc_attr( get_the_author_meta( 'postSearch', $user->ID ) ); ?>" class="regular-text" /><br />
            <span class="description"><?php _e("Por favor ingresa tu dirección."); ?></span>
            <div id="datafetch"></div>
        </td>
    </tr>
    </table>
<?php }


// Llamada Ajax de jQuery aquí
add_action( 'admin_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">

    (function($){
        var searchRequest = null;

        jQuery(function () {
            var minlength = 3;

            jQuery("#postSearch").keyup(function () {
                var that = this,
                value = jQuery(this).val();

                if (value.length >= minlength ) {
                    if (searchRequest != null) 
                        searchRequest.abort();
                    searchRequest = jQuery.ajax({
                        type: "POST",
                        url: "<?php echo admin_url('admin-ajax.php'); ?>",
                        data: {

                            action: 'data_fetch',
                            search_keyword : value

                        },
                        dataType: "html",
                        success: function(data){
                            // necesitamos verificar si el valor es el mismo
                            if (value==jQuery(that).val()) {
                                jQuery('#datafetch').html(data);
                            }
                        }
                    });
                }
            });
        });
    }(jQuery));
</script>

<?php
}


// La función ajax
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['search_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(); 
}
28 ene 2019 11:29:07
1
-2

He estado usando este plugin:

ajax-search-pro-for-wordpress-live-search-plugin

es el mejor plugin

y puedes hacer esto en 5 segundos usándolo.

He utilizado este plugin en muchos de mis proyectos.

22 sept 2016 02:17:29
Comentarios

Perdón por mencionarlo (y no lo tomes como algo personal) pero por favor ¡no respondas sugiriendo un plugin! Sé que los usuarios aquí en wpse no pueden agregar un comentario hasta que tienen una cierta cantidad de puntos de reputación. También es un hecho conocido que wpse está destinado a pedir ayuda con código y no para encontrar un plugin, para eso está el repositorio en WordPress.org. Peor aún, tu consejo es para un plugin comercial de terceros. En mi humilde opinión, esto no está bien y marcaré esta respuesta.

Charles Charles
23 sept 2016 13:52:12