Ajax filter with custom taxonomies

The problem seems to be in the checks you are performing in the php function that handles the ajax reguest.

The first if condition checks if both categoryfilter1 and categoryfilter2 properties are set the the $_POST, and then you have else.

Your code will never enter else because, from what I can see, you will always have at least one categoryfilter set at a given time.

I suggest using the following if conditions

    if ((isset($_POST['categoryfilter1']) && !empty($_POST['categoryfilter1'])) && (isset($_POST['categoryfilter2']) && !empty($_POST['categoryfilter2']))) {
        // both properties are set and have value (not empty)
    } elseif ((isset($_POST['categoryfilter1']) && !empty($_POST['categoryfilter1'])) && (!isset($_POST['categoryfilter2']) || empty($_POST['categoryfilter2']))) {
        // only categoryfilter1 is set and has value and categoryfilter2 is either not set or set but has no value
    } elseif ((!isset($_POST['categoryfilter1']) || empty($_POST['categoryfilter1'])) && (isset($_POST['categoryfilter2']) && !empty($_POST['categoryfilter2']))) {
        // only categoryfilter2 is set and has value and categoryfilter1 is either not set or set but has no value
    }

This checks should handle all your possible outcomes

EDIT

To see the content of $_POST you can use PHP error_log, I use it all the time in development, it helps with displaying the content that you usually can’t output to the screen.

When using filters or ajax requests this can help because this are processes that happen on the backend.

error_log(print_r($_POST, true), 3, __DIR__ . '/log.txt');
error_log("\r\n\r\n", 3, __DIR__ . '/log.txt');

This code will create a new file named log.txt and will contain the content of $_POST.

If your ajax code is located in functions.php, the log.txt file will be in the same directory as functions.php.

After you are done remove the file, if you can’t, delete all content inside of it.

EDIT, after seeing log

The conditions can be even simpler looking at the content of $_POST, try this

if (isset($_POST['categoryfilter1']) && isset($_POST['categoryfilter2'])) {
    // both are set
} elseif (isset($_POST['categoryfilter1']) && !isset($_POST['categoryfilter2'])) {
    // only categoryfilter1 is set
} elseif (!isset($_POST['categoryfilter1']) && isset($_POST['categoryfilter2'])) {
    // only categoryfilter2 is set
}

ALSO

Just noticed that for a single tax_query you use

$args['tax_query'] = array(
    'taxonomy' => 'group',
    'field' => 'id',
    'terms' => $_POST['categoryfilter1']
);

This is incorrect, it should be like this

$args['tax_query'] = array(
    array(
        'taxonomy' => 'group',
        'field' => 'id',
        'terms' => $_POST['categoryfilter1']
    )
);

tax_query expects an array, in that array you need to pass each taxonomy as its own array

Leave a Comment