admin管理员组

文章数量:1435859

Good morning everyone, I am trying to filter posts using ajax by custom fields and custom taxonomy values from a custom post type. Ajax request works fine, It retrieves all needed data to display, but I am not able to handle pagination links.

This is my JQuery request code:

$('#boton-filtrar').click(function (e){
  let filter = $('#formulario-filtro');

  $.ajax({
    url: filter.attr('action'),
    data: filter.serialize(), 
    type: filter.attr('method'),
    beforeSend: function() {
      $('#boton-filtrar').prop('disabled', true);
      $('#boton-filtrar').html('<span class="spinner-border spinner-border-sm"></span>Buscando retiros...');
    },
    success: function(data) {
      mostrar_filtros(false);
      $('#despliegue-retiros').html(data); 
      $('#boton-filtrar').prop('disabled', false);
      $('#boton-filtrar').html('<span>Aplicar filtros</span>');
    },
    error:function(data) {
      console.error(data);
    }
  });
  return false;
});

And this is the main function:

function filtrar_posts() {
$peticion_fecha_inicio = isset($_POST['fecha-inicio']) && !empty($_POST['fecha-inicio']) 
                    ? date("d-m-Y", strtotime($_POST['fecha-inicio'])) : '';
$peticion_fecha_fin = isset($_POST['fecha-fin']) && !empty($_POST['fecha-fin']) 
                    ? date("d-m-Y", strtotime($_POST['fecha-fin'])) : '';
$terminos_categoria = isset($_POST['categoria']) && !empty($_POST['categoria']) 
                    ? $_POST['categoria'] : get_terms('categoria-retiro', array('get' => 'all', 'fields' => 'ids'));
$terminos_provincia = isset($_POST['provincia']) && !empty($_POST['provincia']) 
                    ? $_POST['provincia'] : get_terms('provincia', array('get' => 'all', 'fields' => 'ids'));
$terminos_ciudad = isset($_POST['ciudad']) && !empty($_POST['ciudad']) 
                    ? $_POST['ciudad'] : get_terms('ciudad', array('get' => 'all', 'fields' => 'ids'));
$terminos_alojamiento = isset($_POST['alojamiento']) && !empty($_POST['alojamiento']) 
                    ? $_POST['alojamiento'] : get_terms('alojamiento', array('get' => 'all', 'fields' => 'ids'));

set_query_var( 'paged', isset($_POST['paginado']) && !empty($_POST['paginado']) ? $_POST['paginado'] : 1 );
$paginado = get_query_var( 'paged' );

$dia_fecha_inicio = ''; 
$mes_fecha_inicio = ''; 
$anio_fecha_inicio = ''; 
$fecha_inicio = '';

$dia_fecha_fin = ''; 
$mes_fecha_fin = ''; 
$anio_fecha_fin = ''; 
$fecha_fin = '';

if ($peticion_fecha_inicio) {
    $dia_fecha_inicio = substr($peticion_fecha_inicio, 0, 2);
    $mes_fecha_inicio = substr($peticion_fecha_inicio, 3, 2);
    $anio_fecha_inicio = substr($peticion_fecha_inicio, 6, 4);

    $fecha_inicio = $anio_fecha_inicio . $mes_fecha_inicio . $dia_fecha_inicio;
}

if ($peticion_fecha_fin) {
    $dia_fecha_fin = substr($peticion_fecha_fin, 0, 2);
    $mes_fecha_fin = substr($peticion_fecha_fin, 3, 2);
    $anio_fecha_fin = substr($peticion_fecha_fin, 6, 4);

    $fecha_fin = $anio_fecha_fin . $mes_fecha_fin . $dia_fecha_fin;
}

$meta_query = '';

if ($peticion_fecha_inicio && $peticion_fecha_fin) {
    $meta_query = array(
        'relation' => 'AND',
        array(
            'key'       => 'fecha_de_inicio',
            'compare'   => '>=',
            'value'     => $fecha_inicio,
        ),
        array(
            'key'       => 'fecha_de_finalizacion',
            'compare'   => '<=',
            'value'     => $fecha_fin,
        )
    );
}

if ($peticion_fecha_inicio && !$peticion_fecha_fin) {
    $meta_query = array(
        'relation' => 'AND',
        array(
            'key'       => 'fecha_de_inicio',
            'compare'   => '=',
            'value'     => $fecha_inicio,
        )
    );
}

if (!$peticion_fecha_inicio && $peticion_fecha_fin) {
    $meta_query = array(
        'relation' => 'AND',
        array(
            'key'       => 'fecha_de_finalizacion',
            'compare'   => '=',
            'value'     => $fecha_fin,
        )
    );  
}

$args = array(
    'post_type' => 'retiro',
    'posts_per_page' => 4,
    'paged' => $paginado,
    'meta_query' => $meta_query,
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'categoria-retiro',
            'field'    => 'term_id',
            'terms'    => $terminos_categoria
        ),
        array(
            'taxonomy' => 'provincia',
            'field'    => 'term_id',
            'terms'    => $terminos_provincia
        ),
        array(
            'taxonomy' => 'ciudad',
            'field'    => 'term_id',
            'terms'    => $terminos_ciudad
        ),
        array(
            'taxonomy' => 'alojamiento',
            'field'    => 'term_id',
            'terms'    => $terminos_alojamiento
        )
    ),
);
$query = new WP_Query( $args );

$resultado = '';

if( $query->have_posts() ) :
    while( $query->have_posts() ): $query->the_post();
        $id = get_the_ID();
        $ciudad = get_the_terms($id, 'ciudad');
        $provincia = get_the_terms($id, 'provincia');

        $formato = 'd F, Y';
        $fecha = strtotime(get_field('fecha_de_inicio'));
        $fechasalida = date_i18n($formato, $fecha);

        $fechaRetorno = strtotime(get_field('fecha_de_finalizacion'));
        $fechaRetorno = date_i18n($formato, $fechaRetorno);

        $resultado .= '<div class="col-lg-4 col-md-6 col-sm-12 pb-4">';
        $resultado .= '  <div class="card">';
        $resultado .= '    <div class="imagen-destacada">';
        $resultado .=            get_the_post_thumbnail($id, 'retirosDestacada', array('class' => 'img-fluid card-img-top'));
        $resultado .= '      <a class="mas-info" href="'. get_the_permalink() .'">';
        $resultado .= '        <img class="img-fluid" src="' . get_stylesheet_directory_uri() . '/img/mas-informacion-retiros.png">';
        $resultado .= '      </a>';
        $resultado .= '    </div>';
        $resultado .= '    <div class="card-body">';
        $resultado .= '      <a id="enlaces-pagina-retiros" href="' . get_the_permalink() . '">';
        $resultado .= '        <h3 id="titulo-pagina-retiros" class="pb-2 card-title"> ' . get_the_title() . '</h3>';
        $resultado .= '      </a>';
        $resultado .= '      <p><i class="fas fa-map-marker-alt pr-2"></i>' . $ciudad[0]->name .', ' .  $provincia[0]->name . '</p>';
        $resultado .= '      <p><i class="fas fa-calendar-check pr-2"></i>' . $fechasalida . '</p>';
        $resultado .= '      <p><i class="fas fa-calendar-times pr-2"></i>' . $fechaRetorno . '</p>';
        $resultado .= '      <p><i class="fas fa-money-bill-alt pr-2"></i>' . get_field('precio') . '</p>';
        $resultado .= '    </div>';
        $resultado .= '  </div>';
        $resultado .= '</div>';
    endwhile;

    $resultado .= '<ul class="paginador pt-4 text-center">';

    if (get_previous_posts_link('&nbsp;&nbsp;Anterior', $query->max_num_pages)) {
        $resultado .= '  <li><button type="button" class="btn btn-primary btn-sm mr-4 btn-paginado"><i class="fas fa-arrow-alt-circle-left"></i>' . get_previous_posts_link('&nbsp;&nbsp;Anterior', $query->max_num_pages) . '</button></li>';
    }

    if (get_next_posts_link('Siguiente&nbsp;&nbsp;', $query->max_num_pages)) {
        $resultado .= '  <li><button type="button" class="btn btn-primary btn-sm btn-paginado">' . get_next_posts_link('Siguiente&nbsp;&nbsp;', $query->max_num_pages) . '<i class="fas fa-arrow-alt-circle-right"></i></button></li>';
    }

    $resultado .= '</ul>';

    wp_reset_postdata();
    echo $resultado;
else :
    echo 'No se han encontrado posts';
endif;

die();
}
add_action('wp_ajax_filtrar_posts', 'filtrar_posts'); 
add_action('wp_ajax_nopriv_filtrar_posts', 'filtrar_posts');

This is how I get page number

$('.btn-paginado').click(function (e) { 
  e.preventDefault();
  let url = $(this).find('a').attr('href');
  let page = 0;

  if (url.indexOf('=') != -1) {
    page = url.substring(url.indexOf('=') + 1, url.length);
  } else {
    let cleanUrl = url.substring(0, url.length - 1);
    page = cleanUrl.substring(cleanUrl.lastIndexOf('/') + 1, cleanUrl.length);
  }
  $('#paginado').val(page);
  $('#boton-filtrar').click();
});

Initial state. Showing 4 posts per page having 5 posts

First click state. It shows last post, but next button appears. It shuld be prev button.

By using this code, pagination is not working. How can I handle these links?

Thanks In advance

本文标签: How to display custom post type pagination buttons when processing AJAX request