Filtro de categorías con Ajax
Sé que es mucho pedir, pero no logro resolver esto.
Encontré esta página: http://www.bobz.co/ajax-filter-posts-tag/#comment-28112
Muestra cómo hacer un filtro dinámico para etiquetas de posts.
Quería cambiarlo para categorías de posts, pero no logro hacerlo funcionar.
Coloqué este código en mi functions.php
function ajax_filter_posts_scripts() {
// Registrar script
wp_register_script('afp_script', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Crear nonce que usaremos después para verificar la petición AJAX
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
// Script para obtener posts
function ajax_filter_get_posts( $taxonomy ) {
// Verificar nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permiso denegado');
$taxonomy = $_POST['taxonomy'];
// Consulta WP
$args = array(
'category_name' => $taxonomy,
'post_type' => 'post',
'posts_per_page' => 10,
);
// Si no se establece taxonomía, eliminar clave del array y obtener todos los posts
if( !$taxonomy ) {
unset( $args['category_name'] );
}
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<?php else: ?>
<h2>No se encontraron posts</h2>
<?php endif;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
y luego en mi plantilla de página coloqué este código:
//en mi archivo de plantilla
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
);
$query = new WP_Query( $args );
function tags_filter() {
$tax = 'category';
$terms = get_terms( $tax );
$count = count( $terms );
if ( $count > 0 ): ?>
<div class="post-tags">
<?php
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $tax );
echo '<a href="' . $term_link . '" class="tax-filter" title="' . $term->slug . '">' . $term->name . '</a> ';
} ?>
</div>
<?php endif;
}
Cuando cargo mi plantilla de página, el sitio carga mi contenido y muestra los botones de filtro de categorías, pero cuando hago clic en cualquiera de los botones, devuelve "No se encontraron posts".
Esto me hace pensar que hice algo mal en mi archivo functions, pero no puedo identificar qué es.
¿Alguien puede ver algo que haya hecho mal aquí?

¿No estás seguro si has resuelto esto o no? Estaba buscando una manera de integrar esto dentro de una página y filtrar publicaciones por categoría.
Logré que esto funcione para mostrar todas las categorías y las publicaciones relacionadas. Pon esto en functions.php
function ajax_filter_posts_scripts() {
// Cargar script
wp_register_script('afp_script', get_template_directory_uri() . '/js/ajax-filter-posts.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Crear nonce que usaremos más tarde para verificar la solicitud AJAX
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
// Script para obtener publicaciones
function ajax_filter_get_posts( $taxonomy ) {
// Verificar nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permiso denegado');
$taxonomy = $_POST['taxonomy'];
// WP Query
$args = array(
'category_name' => $taxonomy,
'post_type' => 'post',
'posts_per_page' => 10,
);
echo $taxonomy;
// Si la taxonomía no está establecida, elimina la clave del array y obtiene todas las publicaciones
if( !$taxonomy ) {
unset( $args['tag'] );
}
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<?php else: ?>
<h2>No se encontraron publicaciones</h2>
<?php endif;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
Luego, agrega esto en tu plantilla de página:
<?php $args = array(
'post_type' => 'post',
'posts_per_page' => 10,
);
$query = new WP_Query( $args );
$tax = 'category';
$terms = get_terms( $tax );
$count = count( $terms );
if ( $count > 0 ): ?>
<div class="post-tags">
<?php
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $tax );
echo '<a href="' . $term_link . '" class="tax-filter" title="' . $term->slug . '">' . $term->name . '</a> ';
} ?>
</div>
<?php endif;
if ( $query->have_posts() ): ?>
<div class="tagged-posts">
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php endwhile; ?>
</div>
<?php else: ?>
<div class="tagged-posts">
<h2>No se encontraron publicaciones</h2>
</div>
<?php endif; ?>
¡Espero que esto ayude a resolver tus problemas!
