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

-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 for a word and with AJAX load the first result in the div #resultado_search.

I searched the tutorials, but I did not understand them right, there are some that include the whole code in functions.php, others put a part in an ajax.js file.

It does not have to be a search in the whole post, it can be a search only in the title of the post.

    
asked by anonymous 07.08.2018 / 06:12

1 answer

1

The ideal is to separate files do not do 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 must create an event with jquery or pure javascript for this input, I 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, to do this, place the following lines of code in your theme's functions:

    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 inside your JS, so there in the "my-script" you put the name of the JS you are going to manipulate.

Once you have done this you will do the following in the 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 title searched for.

Well, as soon as you've built this in your javascript we can go to the functions.php

In the functions.php of your theme you will create a function with the same name that you put in the action value, there in the datasend (no 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 above code is the method I use and it works kkkk, if you have some better alternative I will follow the post, the code was thought in a scenario where you do not have the posts listed and have to search them in the base, if the post is already on the page, just filtering through js without needing ajax, I hope I have helped.

    
07.08.2018 / 14:39