He estado trabajando en un proyecto de tema de WordPress de comercio electrónico personalizado. Acabo de hacer todo bien, pero me quedé atascado en el bucle al intentar cargar la siguiente página de publicaciones en bucle a través de AJAX.
En realidad, he visto en muchos sitios y temas de WP como Flatsome, cuando alguien hace clic en Mostrar más publicaciones, carga la página siguiente, es decir, https://abc.xyz/page2/ sin recargar la página. Simplemente actualiza el contenido en la misma página y agrega la siguiente página justo debajo de la primera página.
Intenté codificar un JQuery corto para poder cargar la página siguiente de esta manera, pero no parecía funcionar. ¿Puede alguien averiguar qué está mal en mi código y cómo podría solucionarse?
archivo.php
<div class="posts"> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <div class="entry-content"> <?php the_title(); ?> // just to test if it works // </div> <?php endwhile; ?> <div class="posts-navigation"> <a>Load More</a> </div> <?php endif;?> </div>Mi AJAX jQuery
$('body').on('click', '.posts-navigation a', function (e) { let $page = $(this).attr('href'); e.preventDefault(); //update the button so the user knows something is happening $(this).text('Loading...').addClass('loading'); $.get($page, function (data) { //filter the received data and store the required vars let $items = $(data).find('.entry-content'), $nextpage = $(data).find('.posts-navigation a').attr('href'), $container = $('.posts'); //append the new posts to the posts wrapper $container.append($items); //now we can update the button so it's ready for the next batch of posts, and at the same time check if there is another link to the next page $('.posts-navigation a').text('Load More').attr('href', $nextpage); //check if there are no more posts to load by looking for the href in the received data //if there is no next page link, it will be undefined. hence, we can then hide the pagination button (or remove() if you wish). if ($nextpage === undefined) { $('.posts-navigation a').hide(); } }); });Por favor, hágame saber cómo podría solucionarse.