Damian_B
Damian_B

Reputation: 75

Query WP Custom Posts with ACF Taxonomy field

I need query custom posts with ACT Taxonomy field. I created this code:

My Taxonomy ACF field returns Term Object and allows multiselect but this code works only for last selected term. I need query all selected terms.

<?php
$album_count = get_sub_field('album-count');
$album = get_sub_field('album-custom-category'); ?>
<?php foreach ( $album as $album ); ?>
<?php $the_query = new WP_Query( 
    array(
    'post_type' => 'gallery',
    'orderby' => 'date',
    'posts_per_page' => 6,
    'tax_query' => array(
        array(
            'taxonomy' => 'albums',
            'field'    => 'slug',
            'terms'    => array( $album->slug ),
        ),
    ),
    )
    ); 
    ?>

Where is my mistake?

Upvotes: 3

Views: 6588

Answers (1)

Noah
Noah

Reputation: 570

You are doing a foreach of all the terms and then setting the value of the query inside the foreach which will of course only bring in the last term because you’re overriding the previous value every time. Since it is a multi select, you should just be able to pass the whole album array to the WP_Query. Also, make sure you are returning the term ID value in ACF, NOT, the Term Object. You’ll then update your code to be something like this:

<?php
$album_count = get_sub_field('album-count');
$albums = get_sub_field('album-custom-category'); ?>

<?php $the_query = new WP_Query( 
  array(
    'post_type' => 'gallery',
    'orderby' => 'date',
    'posts_per_page' => 6,
    'tax_query' => array(
      array(
        'taxonomy' => 'albums',
        'field'    => 'term_id', // This line can be removed since it’s the default. Just wanted to show that you’re passing the term is instead of slug.
        'terms'    => $albums,
      ),
    ),
  ),
); ?>

Upvotes: 1

Related Questions