Skip to content

Instantly share code, notes, and snippets.

@interactiveRob
Created February 7, 2023 23:27
Show Gist options
  • Save interactiveRob/c4f0b7add5254b70c40e1f040897076a to your computer and use it in GitHub Desktop.
Save interactiveRob/c4f0b7add5254b70c40e1f040897076a to your computer and use it in GitHub Desktop.
Modify WP_Query with ACF taxonomy field data
<?php
/*———— -Logic goes here, build $props, then include the markup template- ————*/
$defaults = get_field('recent_posts') ?: [];
$posts_to_show = $defaults['posts_to_show'];
$query_args = [
'post_status' => 'publish',
'paged' => 1,
'post_type' => 'post',
'posts_per_page' => $posts_to_show,
];
$selected_posts = isset($defaults['selected_posts'])
? $defaults['selected_posts'] : [];
if(!empty($selected_posts)):
$selected_post_ids = array_map(function($post){
return $post->ID;
}, $selected_posts);
$query_args = array_merge($query_args, [
'post__in' => $selected_post_ids,
]);
endif;
$filter_by_category = $defaults['category_filter'];
/* only filter by category if checkbox field
is checked (yields) boolean TRUE value */
if($filter_by_category == TRUE):
$selected_terms = $defaults['categories_to_pull'];
/* build an array of selected category ids because
that's how WP_Query wants it */
$selected_term_ids = array_map(function($term){
return $term->term_id;
}, $selected_terms);
/* if any categories are selected, modify the posts query
using the "category__in" parameter.
https://developer.wordpress.org/reference/classes/wp_query/ */
if(!empty($selected_term_ids)):
$query_args = array_merge($query_args, [
'category__in' => $selected_term_ids,
]);
endif;
endif;
$query = new WP_Query($query_args);
$items = $query->get_posts();
wp_reset_postdata();
$defaults = array_merge($defaults,
[
'articles' => $items,
]
);
$props = array_merge($defaults, isset($props) ? $props : []);
$component_name = basename(__DIR__);
secu_get_component_template($component_name, $props);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment