WP_Query by Category From an ACF Taxonomy Field

Quick Summary
- Read a posts_per_page Number field and a posts_ctg Taxonomy field with get_field(), then pass the selected term IDs to category__in in WP_Query.
- category__in works with the built-in Category taxonomy, so use a tax_query for custom taxonomies; a Term ID Return Value skips the foreach.
- Set $f_post_id to leave out a post such as a featured one, replace the the_title() line with your own markup, and keep wp_reset_postdata() after the loop.
With Advanced Custom Fields (ACF) you can let editors choose categories and a number of posts on a page, then build a WP_Query from those choices. This snippet reads two ACF fields and queries posts from the selected categories.
It expects two fields on the current page: posts_per_page (a Number field) and posts_ctg (a Taxonomy field for categories, with Return Value set to Term Object). Put the code in the template that displays that page, because get_field() reads from the current post by default.
$posts_per_page = get_field('posts_per_page');
$g_terms = get_field('posts_ctg');
//create term array
$post_ctgs = array();
if( $g_terms ){
foreach( $g_terms as $g_term ){
$term_ID = $g_term->term_id;
$post_ctgs[] = $term_ID;
}
}
//query
$f_post_id = 0; // ID of a post to leave out, such as a featured post (0 = none)
$article_args = array(
'post_type' => 'post',
'posts_per_page' => $posts_per_page,
'category__in' => $post_ctgs,
'post__not_in' => array($f_post_id),
);
$articles = new WP_Query($article_args);
while ($articles->have_posts()): $articles->the_post();
// your post markup, for example the linked title
the_title( '<h3><a href="' . esc_url( get_permalink() ) . '">', '</a></h3>' );
endwhile;
wp_reset_postdata();How it works
- The
foreachloop collects theterm_idof each selected term into$post_ctgs. If you set the field’s Return Value to Term ID instead, ACF returns the IDs directly and you can skip the loop. - If no category is selected,
$post_ctgsstays empty.WP_Querythen ignorescategory__inand lists posts from all categories. category__inreturns posts from any of those categories. It works with the built-in Category taxonomy; for a custom taxonomy, use atax_queryinstead, as in querying posts by a custom taxonomy term ID.post__not_inexcludes the post whose ID is in$f_post_id, for example a featured post shown above the list. Set it to that post’s ID; with0no post is left out.- The loop prints each post’s title as a link. Replace the
the_title()line with your own post markup.wp_reset_postdata()then restores the current page’s post data.
For queries driven by ACF fields like this, built into your theme, see my WordPress development services.
Related articles
- WooCommerce products from a category ID stored in ACF: the same idea for products
- why ACF still suits custom WordPress sites: where editor-chosen settings like these fit
