• Sam

    (@forbiddenchunk)


    I’ve been using ACF to have a custom field in flexible content that lets admin choose the categories for the page blog (standard Posts) using multi-checkbox.

    I’ve tried to output this on the front end with;

    <?PHP 
        $terms = get_sub_field('category');
    
        $args = array( 
            'posts_per_page' => get_sub_field('number_of_articles'),
            'order' => 'DESC',
            // 'cat' => '119,77'
            'cat' => $terms
        );
        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post(); 
    ?>
        <?php get_template_part( 'components/blog_article' ); ?>
    <?php endwhile; ?>      
    <?php wp_reset_query(); ?>

    And get an error and can’t seem to find a solution that’s been done before.

    I know I can get the list of categories using;

    <?php 
    	$terms = get_sub_field('category');
    	if( $terms ): 
    ?>
        <?php foreach( $terms as $term ): ?>
            <p><?php echo esc_html( $term->term_id ); ?></p>
        <?php endforeach; ?>
    <?php endif; ?>

    But struggling to work out how to merge the two so it outputs the chosen posts.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    While the “cat” argument of WP_Query can be made to work, I recommend using “tax_query” instead. While it’s more complex to use, it’s much more flexible. Once you learn to use it correctly it’ll work for any taxonomic need that might arise.

    I’ve not used ACF much, so I’m not sure what sort of data get_sub_field() returns. It is apparently an array of WP_Term objects. What you need for “tax_query” is an array of just term IDs. So loop through the array of term objects like in your second snippet, but collect the IDs into an array instead of echoing out. Use that array as the “terms” element in your “tax_query” argument array.

    Lets say the IDs were collected into an array assigned to $term_ids. Your “tax_query” argument would then be:

        'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'field'    => 'term_id',
                'terms'    =>  $term_ids,
            ),
        ),
    Thread Starter Sam

    (@forbiddenchunk)

    @bcworkz that worked thanks!

    I was had read up on that method but couldn’t get it to work.

    Thanks for the help ??

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘ACF Mutli Taxonomy with WP Query’ is closed to new replies.