How to make your AJAX filter works properly:
-
As I said in the comments, add the
data-category
attribute to the<a>
having the CSS classjs-filter-item
in theforeach
loop in yourarchive-projetos.php
template:// * Wrapped for brevity. foreach ( $categories as $cat ) : ?> <li><a class="js-filter-item" href="<?= get_category_link( $cat->term_id ); ?>" data-category="<?= $cat->term_id; ?>" ><?= $cat->name; ?></a></li> <?php endforeach; ?>
And if you wonder why add that attribute, then it’s because in
filter.js
, the script is reading the category ID via$(this).data('category')
which is equivalent to$( this ).attr( 'data-category' )
. -
In the
filter_ajax()
function infunctions.php
, replace this:$query = new WP_Query($args); if(isset($category)) { $args['category__in'] = array($category); }
with this:
if ( ! empty( $category ) ) { $args['tax_query'] = array( array( 'taxonomy' => 'Tipos de Construção', 'terms' => $category, ), ); } $query = new WP_Query( $args );
I.e. Switch the position (of the
new WP_Query()
call and theif
block) and then use thetax_query
parameter and notcategory__in
which is for the defaultcategory
taxonomy only. -
Also in that
filter_ajax()
function, replace the$category = $_POST['projetos'];
with$category = $_POST['category'];
because your JS script is sending the category ID in a (POST) input namedcategory
and notprojetos
.However, you should always check if an array item is actually set before attempting to use it, so you would want to use
$category = $_POST['category'] ?? '';
or the old way (prior to PHP 7):$category = isset( $_POST['category'] ) ? $_POST['category'] : '';
.
Additional Notes
Even though the Tipos de Construção
does work as the taxonomy name, i.e. the first parameter you pass to register_taxonomy()
, you should actually use a slug like tipos_de_construcao
because the documentation says:
$taxonomy
is the name of the taxonomy. Name should only contain lowercase letters and the underscore character, and not be more than
32 characters long (database structure restriction). Default: None
So you should try to fix the taxonomy name, i.e. use a slug. It will take time, but it will be a better option in the long run. =)