Cómo filtrar entradas por taxonomía usando AJAX
Encontré esta publicación que describe cómo filtrar posts por categoría con Ajax y funciona muy bien, pero también quiero filtrar mis taxonomías personalizadas de la misma manera y no logro que funcione. Me muestra todas las entradas en lugar de solo las entradas de mi taxonomía.
Sé que el menú necesita cambiarse a get_the_terms
en lugar de get_the_categories
, pero específicamente necesito ayuda sobre qué cambiar en la función jQuery y en la función PHP al final. Intenté agregar un tax_query
llamando a mi taxonomía pero aún no muestra los posts correctos. ¿Alguien puede ayudarme a orientarme en la dirección correcta?

¡Lo resolví! Aquí está el código que utilicé:
Añadir a functions.php
:
add_action( 'wp_ajax_nopriv_load-filter2', 'prefix_load_term_posts' );
add_action( 'wp_ajax_load-filter2', 'prefix_load_term_posts' );
function prefix_load_term_posts () {
$term_id = $_POST[ 'term' ];
$args = array (
'term' => $term_id,
'posts_per_page' => -1,
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'yourtaxonomyhere', // Reemplazar con tu taxonomía
'field' => 'id',
'terms' => $term_id,
'operator' => 'IN'
)
)
);
global $post;
$myposts = get_posts( $args );
ob_start (); ?>
<ul class="list">
<?php foreach( $myposts as $post ) : setup_postdata($post); ?>
<li><a href="<?php the_permalink(); ?>" id="post-<?php the_ID(); ?>"><?php echo get_post_meta($post->ID, 'image', $single = true); ?></a><br />
<?php the_title(); ?></li>
<?php endforeach; ?>
</ul>
<?php wp_reset_postdata();
$response = ob_get_contents();
ob_end_clean();
echo $response;
die(1);
}
Script jQuery:
<script>
function term_ajax_get(termID) {
jQuery("a.ajax").removeClass("current");
jQuery("a.ajax").addClass("current"); // añade la clase current al elemento del menú que se está mostrando para poder estilizarlo con CSS
jQuery("#loading-animation").show();
var ajaxurl = 'http://yourdomain.com/wp-admin/admin-ajax.php'; // Cambiar por tu dominio
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "load-filter2", term: termID },
success: function(response) {
jQuery("#category-post-content").html(response);
jQuery("#loading-animation").hide();
return false;
}
});
}
</script>
No estoy usando una función para listar las categorías, simplemente las listo por separado. Reemplaza el número con el ID de tu término:
<ul class="nav">
<li id="term-166"><a class="yourtermname ajax" onclick="term_ajax_get('166');" href="#">Nombre de tu Término</a></li>
<li id="term-354"><a class="yourtermname ajax" onclick="term_ajax_get('354');" href="#">Nombre de tu Término</a></li>
</ul>
Además, si quieres filtrar etiquetas en lugar de términos, reemplaza:
'term'
con'tag__in'
,$term_id
con$tag_id
- y cambia
'taxonomy' => 'yourtaxonomyhere'
por'taxonomy' => 'post_tag'
.

Te sugiero que uses un shortcode para mostrar la taxonomía de tu elección: crea una clase para declarar el shortcode y llama a esta función
public function shortcode($atts)
{
extract(shortcode_atts( array(
'data' => 'taxonomy',
'taxonomy' => 'category',
//argumentos get_terms
'parent' => 0, //por defecto solo obtiene términos de nivel superior
'exclude'=>'',
'type'=>'radio' // checkbox,radio
), $atts,'astSearchInput' ));
$arrStr =array();
$arrStr[]= "<div class='astSearchInput " . $taxonomy. "' taxonomy='" .$taxonomy. "'>" ;
if ($type=="checkbox" || $type=="radio")
{
if ($data=="taxonomy")
{
//echo $datatata;
$arrValues=get_terms($taxonomy, array("parent"=>$parent, "exclude"=>$exclude));
}
if ($type=="checkbox")$arrStr[]= $this->inputCheckBox($arrValues,$atts);
if ($type=="radio")$arrStr[]= $this->inputRadio($arrValues,$atts);
}
$arrStr[]= "</div>";
$str=join("\n",$arrStr);
return $str ;
}
function inputCheckBox($arrValues,$attr)
{
$arrStr =array();
$arrStr[]='<div class="formcb">';
foreach($arrValues as $k=>$term)
{
$title=$term->name; //$term->description
// print_r($term);
$id="cb" . $term->term_id;
$arrStr[]='<div class="cb"><input class="astInpuntTerm astcheckBox" type="checkbox" id="' . $id .'" value="' . $term->term_id . '" ><label for="' . $id . '">' . $title. '</label></div>';
}
$arrStr[]='</div>';
$str=join("\n",$arrStr);
return $str;
}
http://www.webmasterbulletin.net/wordpress-ajax-taxonomy-search-shortcode

Tuve un problema similar.
El código es bueno, pero necesita una pequeña modificación para funcionar.
$args = array (
'term' => $term_id,
'posts_per_page' => -1,
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'yourtaxonomyhere',
'field' => 'id',
'terms' => $term_id,
'operator' => 'IN'
)
),
'post_type' => 'yourcustomposttype', // <== esto faltaba
'posts_per_page' => 10,
'order' => 'DESC'
);
