búsqueda en vivo ajax para títulos de entradas
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>
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();
}

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

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)

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

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.

/* 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();
}

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.
