Codarz360
Codarz360

Reputation: 436

Wordpress WP_Query terms with array variable

I'm trying to display posts dependant on their tags.

I have some functionality that when I click the term buttons they send off an array of data formatted liked this:

array(
   [0] => 'some tag name',
   [1] => 'another tag name'
)

In the function below I format that to look something like this:

'timbermode','bathroom'

I then pass that data into the "terms" section but nothing every gets returned.

function ajax_filter_get_posts( $taxonomy ) {

    $taxonomy = $_POST['taxonomy'];

    $data = json_decode(stripslashes($taxonomy));

    $stringData = '"' . implode('","', $data) . '"');

   //$stringData = "array('" . implode("','", $data) . "')";

    // WP Query
    $args = array(
    'post_type' => 'gallery',
    'posts_per_page' => 8,
    'tax_query' => array(
            array(
                'taxonomy' => 'gallery_tag',
                'field' => 'slug',
                'operator' => 'IN',
                'terms'    => array($stringData),
            ),
        )
    );

  $query = new WP_Query( $args );

  echo "{$query->request}";
}

If I manually pass in the terms like so:

    // WP Query
    $args = array(
    'post_type' => 'gallery',
    'posts_per_page' => 8,
    'tax_query' => array(
            array(
                'taxonomy' => 'gallery_tag',
                'field' => 'slug',
                'operator' => 'IN',
                'terms'    => array('some term', 'another term'),
            ),
        )
    );

It then works fine. I just can't figure it out.

Any help is appreciated.

Thanks, Codarz

Upvotes: 2

Views: 6602

Answers (1)

Allkin
Allkin

Reputation: 1098

$data is already an array and formated as required. Just set 'terms' => array_values($data).

Upvotes: 2

Related Questions