Esta es mi primera incursión en AJAX, he estado uniendo bits de código de varios tutoriales que probablemente no han ayudado.
Tengo una lista de categorías en mi página de inicio (index.php) y una lista de las publicaciones más recientes. Cuando un usuario hace clic en una categoría, quiero que esta lista de publicaciones se actualice sin actualizar la página. Actualmente, cuando hago clic en un filtro, todas las publicaciones se están cargando en mi contenedor de respuestas (no está filtrando por categoría) y el único contenido que se está cargando es the_content (), aunque mi plantilla (listing-post.php) solicita la miniatura. , la categoría etc.
Estoy usando Bones como mi tema de inicio, por lo tanto, wp_localize_script está en este archivo (está funcionando). Solo he incluido el código que sé que tiene problemas (sé que el resto del sitio y JS funcionan bien).
bones.php
//Add AJAX path to use in load-posts.js
$getPath = array('ajaxURL' => admin_url('admin-ajax.php'));
wp_localize_script('main-js', 'pathToFile', $getPath);
functions.php
//AJAX Category Filter
add_action( 'wp_ajax_load_cat_posts', 'load_cat_posts' );
add_action( 'wp_ajax_nopriv_load_cat_posts', 'load_cat_posts' );
function load_cat_posts () {
$cat_id = get_post_meta($_REQUEST['cat']);
$args = array (
'cat' => $cat_id,
'posts_per_page' => 10,
'order' => 'DESC'
);
$posts = get_posts($args);
ob_start ();
foreach ( $posts as $post ) {
setup_postdata( $post ); ?>
<?php get_template_part( 'partials/listing', 'post'); ?>
<?php } wp_reset_postdata();
$response = ob_get_contents();
ob_end_clean();
echo $response;
die(1);
}
index.php
<?php $categories = get_categories(); ?>
<ul class="category-filters">
<?php foreach ( $categories as $cat ) { ?>
<li id="cat-<?php echo $cat->term_id; ?>">
<a class="<?php echo $cat->slug; ?> ajax" data-cat="<?php echo $cat->term_id; ?>" href="javascript:void(0)"><?php echo $cat->name; ?></a>
</li>
<?php } ?>
</ul>
listing-post.php
<li class="standard-post">
<article id="<?php echo sanitize_title_with_dashes( get_the_title() ); ?>" <?php post_class(); ?> role="article">
<?php if (has_post_thumbnail()) { ?>
<div class="article-image">
<?php the_post_thumbnail(large); ?>
</div>
<?php } ?>
<div class="article-left">
<?php foreach((get_the_category()) as $category) { ?>
<span class="article-category"><?php echo $category->cat_name . ' ';?></span>
<?php } ?>
</div>
<div class="article-right">
<header class="article-header">
<h1 class="article-title"><?php the_title(); ?></h1>
<p class="article-time">
<?php printf( __( '<time class="updated" datetime="%1$s" pubdate>%2$s</time>', 'bonestheme' ), get_the_time(), get_the_time(get_option('date_format'))); ?>
</p>
</header>
<section class="entry-content">
<?php the_content(); ?>
</section>
</div>
</article>
</li>
load-posts.js
function cat_ajax_get(currentCat) {
$('a.ajax').removeClass('current');
$('a.ajax').addClass('current');
$('#loading-animation').show();
$.ajax({
type: 'POST',
url: ajaxurl,
data: {action: 'load_cat_posts', cat: currentCat },
success: function(response) {
$('.article-listing').html(response);
$('#loading-animation').hide();
return false;
}
});
};
ajaxFilters: function() {
$('.category-filters a').on('click', $.proxy(function(clickEvent) {
$clickTarget = $(clickEvent.currentTarget);
var currentCat = $clickTarget.attr('data-cat');
cat_ajax_get(currentCat);
},this));
}