I am trying to create several areas in a site which show 2 recent posts from a specific category, and I want to use a ACF fields to allow the site admin to choose/change the category displayed.
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; ?>
My issue is that the cat =>
part of the query makes no difference to the result. I am getting the 2 most recent posts of all categories rather than the specified one.
How do I get the term object from the sub field to filter my query?
Thanks.
A term object is returned and $cat->ID has no value. This should be causing an error.
I don’t know why your calling esc_html
$cat_id = $cat->term_id;
Yup you’re quite right. I found this just before I saw your reply. I called esc_html simply because I was trying everything I could think of. : )
As always, thank you John!