WP Posts from Custom Field
Outputting posts turned out to be not so simple, especially from a specific category selected by the editor in a custom field. Spent about 2 hours to pull out what I need in the form I wanted:
<?php $term = get_queried_object();
$catid = (int) get_field('proizvolnoe_pole', $term); ?>
<?php $posts = $catid > 0 ? get_posts ("category=$catid&orderby=date&numberposts=10") : []; ?>
<?php if ($posts) : ?> <?php foreach ($posts as $post) : setup_postdata ($post); ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php endforeach; wp_reset_postdata(); endif; ?>
This example uses Advanced Custom Fields (ACF). $term = get_queried_object() selects the current post, page or category that stores the field. Configure the field to return a single category ID; an empty selection produces an empty list.
$catid - variable in which we save the custom field value.
get_field - function returning field value.
proizvolnoe_pole - custom field name.
category=$catid - pass variable $catid to output posts from specified category.
orderby=date - sort order by date.
numberposts=10 - limit output to max 10 posts.
