Loop through ACF taxonomies and output associated posts


I have a page template that loops through all existing post categories and outputs 5 associated posts for each category. I want to change this so it only outputs the categories I have selected in an ACF Taxonomy field on a particular page.

I have set up the page and added the ACF Taxonomy field to this, however I can’t work out how to get the original loop to only use the taxonomies selected here. What’s the best way to achieve this?

I’ve tried passing the taxonomies via get_field('taxonomy_field_name') into the first foreach, however that doesn’t seem to be working

Here’s how I’m looping through the categories/posts:

/* Loop through Categories and Display Posts */
    $post_type = 'post';
    // Get all the taxonomies for this post type
    $taxonomies = get_object_taxonomies( array( 'post_type' => $post_type ) );
    foreach( $taxonomies as $taxonomy ) :
      $terms = get_terms( $taxonomy );
      foreach( $terms as $term ) :
          $args = array(
                  'post_type' => $post_type,
                  'posts_per_page' => 5,  //show all posts
                  'tax_query' => array(
                          'taxonomy' => $taxonomy,
                          'field' => 'slug',
                          'terms' => $term->slug,
          $posts = new WP_Query($args); ?>
          <div class="category-container-row">
          <?php if( $posts->have_posts() ): ?> 
            <div class="category-title">
                    <?php echo '<a href="' . get_site_url() . '/' . $term->slug . '">' . $term->name . '</a>';?>
            <div class="post-listing-row carousel-container">
            <?php while( $posts->have_posts() ) : $posts->the_post(); ?>
            <article class="single-post">
                  <a href="<?php echo get_permalink($post->ID); ?>"><?php  echo get_the_title(); ?></a>
            <?php endwhile; endif; ?>
      <?php endforeach;
    endforeach; ?>


>>> Share a link to this question, just copy and paste the code bellow on your web page <<<

<a href="https://www.wptricks.com/question/loop-through-acf-taxonomies-and-output-associated-posts/">

Loop through ACF taxonomies and output associated posts</a>
, , user108167 2 weeks 0 Answers 20 views 0

Leave an answer