Search post and load it into a div using Ajax in Wordpress

Asked

Viewed 318 times

-1

I have the following structure in wordpress.

<input type="text" id="busca_artigo">
<button id="btn_busca_artigo">Enviar</button>

<div id="resultado_pesquisa"></div>
<button id="volta_artigo">Anterior</button>
<button id="proximo_artigo">Próximo</button>

I want to search a word and with AJAX load the first result in the div #resultado_search.

I searched the tutorials, but, I didn’t understand them properly, there are some that include the whole code in functions.php, others put a part in an ajax.js file.

It doesn’t have to be a search in the whole post, it can be a search only in the post title.

1 answer

1


The ideal is to separate in files not doing everything in functions, what you ask in your question is a little big to put here but I will try to exemplify well, first you should create an event with jquery or pure javascript for this input, I recommend using . on("input") (if you use jquery). Within this input event you must make an ajax request, for this you will need to load a wordpress file called admin-ajax.php, so put in the functions of your theme the following lines of code:

    function Wps_load_scripts() {
     wp_register_script( 'my-script', get_template_directory_uri() . '/js/javascript.js');
     wp_localize_script( 'my-script', 'ajaxLoad_ajaxurl', admin_url('admin-ajax.php') );

      wp_enqueue_script( 'my-script');

    }

    add_action('wp_enqueue_scripts', 'Wps_load_scripts');

The wp_localize_script function will allow you to use this file within your JS, so there in "my-script" you put the JS name that you will handle.

After performing this you will do the following in JS file :

  $content = $(".divquedesejocolocarmeuconteudo");
      $('#meuinput').on('input', function() {
        var title_page , input;
        input = $(this);
        title_page = input.val();

        var datasend = {action: 'load_input_post', title:title_page};
        $.ajax({
          type: "GET",
          data: datasend,
          dataType: "json", //Esse retorno pode ser em HTML tbm
          url: ajaxLoad_ajaxurl, /*Isso daqui é a variavel que passamos pelo 
          localize_script dentro do functions*/
          beforeSend: function() {
                 /* geralmente onde se coloca o loader */
          },     
              success: function(data) {
               if(typeof data != "undefined" && typeof data !== null) { 
                 if(typeof data.conteudo1 != "undefined" && typeof data.conteudo1 !== null) {       
                  $content.html(data.conteudo1);
              }
             }
            }else {
                 /* remover loader */
          }
    });

The variable "datasend" we passed 2 values, action (which is the function that will be called by ajax pro php) and the title that is the searched title.

Very well, as soon as we build this in your javascript we can go to functions.php

In the functions.php of your theme you will create a function with the same name as you put in the action value, there in datasend (in js).

    function load_input_post(){

      $page_title = (isset($_GET['title']) ? $_GET['title'] : '' ); 
      $tipodopost = 'post';
      /* para recuperar a página pelo titulo você pode usar a função get_page_by_title ()*/
      $page = get_page_by_title($pagetitle, OBJECT, $tipodopost);

     /*Pronto, agora a variavel $page armazena todas as informações da página, use como desejar*/
      /* se você for retornar um HTML já construido você deve fazer o seguinte */
      <?php
        ob_start(); 
        $var = "teste";
        $var = "teste2";
      ?> 

      <h1>teste</h1>
      <img src="<?php echo  $var; ?>">
      <img src="<?php echo $var_2; ?>">

      <?php 
      $teste = ob_get_clean();
      /* usei o  ob_get_clean() pois é mais rapido, faça o método que desejar */

      /* para enviar o $teste de volta para seu JS para que possa colocar no conteudo retorno um JSON */

       $response = array();
       $response['conteudo1'] = $teste;
       wp_send_json($response); /*enviado de volta para o js */

    }
add_action('wp_ajax_load_input_post', 'load_input_post');
add_action('wp_ajax_nopriv_load_input_post', 'load_input_post');

/*Essas duas linhas de cima são necessárias para o wp entender que isto acima é uma função para requisição ajax, os nomes "wp-ajax" e "wp-ajax-nopriv" são prefixos, para em seguida surgir o nome da sua função, o nopriv é para usuários não logados*/

HTML example:

<input type="text" id="meuinput">

<div class="divquedesejocolocarmeuconteudo"></div>

The code above is the method I usually use and works kkkk, if you have any better alternative I will be following the post, the code was thought of in a scenario where you do not have the posts listed and have to search them at the base, if the post is already on the page, just do a filter by js without needing ajax, hope to have helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.