0

I'm working on a custom filter that uses checkboxes to choose which categories to show. I'm trying to get it show posts based on selecting more than one category. When I test with hard coded ID's it works as planned, but when I use $_POST[] to get categories dynamically I always get the same posts.

    $cats = $_POST['cats'];
    
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 2,
        'paged' => $_POST['page'],
        'category__in' => $cats, // doesn't work and console on the returned data shows ['6', '2']
        // 'category__in' => ['6', '2'] // works
    );

    $query = new WP_Query($args);

    foreach ( $query->posts as $post ) {
        $results[] = array(
            'post' => $post,
            'img_url' => wp_get_attachment_image_url(get_post_thumbnail_id($post->ID), 'full'),
            'title' => $post->post_title,
            'link' => get_permalink($post->ID),
            'max_page' => $query->max_num_pages,
            'test' => $cats
        );
    }
    
    wp_send_json_success($results);

The 'category__in' => ['6', '2'] works and I get the 5 expected posts but $cats only gives me posts with the ID of 6. I'm not sure where I'm messing up. Any help would be great.

1
  • Try doing a compare of $cats with [ '6', '2' ] (ex: var_dump( $cats === [ '6', '2' ] );) and see if PHP reports that the two variables are equal. If they're not, then there's something askew with the $_POST data.
    – Caleb
    Commented Oct 31 at 23:07

1 Answer 1

0

To get an array from a form POST into PHP, you have to name the form variable with square brackets:

<html>
<body>
<pre>
<?php var_export( $_POST ); ?>
</pre>
<form action="" method="post">
    <label> 4<input type="checkbox" name="cats[]" value="4"></label>
    <label> 5<input type="checkbox" name="cats[]" value="5"></label>
    <label> 6<input type="checkbox" name="cats[]" value="6"></label>
    <input type="submit" value="Submit">
</body>
</html>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.