最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

categories - How to use the Term Object from a custom select field in a query

programmeradmin0浏览0评论

I have a WordPress site in which I want to show 2 recent posts from a specific category. I want to use custom fields (via ACF in this case) to allow the site admin to choose/change the category displayed in each area.

Because there will be several instances of this in one page, I have set up a group of taxonomy fields – settings as follows:

  • Taxonomy: Category
  • Appearance: Select
  • Return Value: Term Object

I am implementing these fields as follows:

<?php if(have_rows('page_sections')) : while(have_rows('page_sections')) : the_row(); ?>
 
 <?php 
  $cat = get_sub_field('category');
  $cat_id = esc_html( $cat->ID );
  $cat_args = array(
   'cat' => $cat_id,
   'nopaging' => false,
   'posts_per_page' => 2,
   'ignore_sticky_posts' => 1
  );
  $cat_query = new WP_Query( $cat_args );
  if ( $cat_query->have_posts() ) : ?>
  <h3><a href="<?php echo esc_url( get_term_link( $cat ) ); ?>"><?php echo esc_html( $cat->name ); ?></a></h3>
  <?php while ( $cat_query->have_posts() ) : $cat_query->the_post(); ?>
   <!-- Displaying post data here -->
  <?php endwhile; ?>
  <?php wp_reset_postdata(); ?>
 <?php else : endif; ?>

<?php endwhile; ?>
<?php else : endif; ?>

The category name and link are generated as expected in the h3 tags on line 14 here, but my issue is that the cat => part of the query makes no difference to the result. Posts are displayed as I expect, but I am getting the 2 most recent posts from ALL categories rather than the specified one.

How do I get the term object from the sub field to filter my query?

Thanks for reading.

发布评论

评论列表(0)

  1. 暂无评论