I'm new to WP_Query and there don't seem to be very many references on how to display posts by ACF relationship. It looks like I'm supposed to use a "meta_query"I have two related custom post types: videos and guests. Each video post of video-category "episodes" has at least one related guest. The ACF relationship field is called "guest_names".
I need to display the latest 3 videos related to the guests for the current video. Lets stipulate for simplicity sake that each video only has one guest.
This is my SQL-ish pseudocode algorithm:
CREATE a new query [my_query] that is not the main query
DISPLAY all posts of type "videos"
WHERE custom taxonomy "video-category" == "episodes"
AND custom taxonomy "post-tags" !== "DEBUG-Hidden"
AND current guest name IN guest_names ACF relationship value
LIMIT 3
I believe the recommended approach is to create a code snippet as a filter? Some have recommended using the pre_get_posts hook and others have not.
This is what I have come up with that sort of works:
// WORKS except the meta filter not working
$my_query = [
'post_type' => 'videos',
'tax_query' => [
'relation' => 'AND',
array(
'taxonomy' => 'video-category',
'field' => 'slug',
'terms' => array('episodes'),
),
],
'meta_key' => 'guest_names',
'meta_value' => '"' . get_the_title() . '"',
'compare' => 'LIKE',
];
return $my_query;
However, it looks like the get_the_title() function might not be working? It would be easier to tell if I could debug it out. I've been working on this for 3 hours now, read through a lot of posts and docs, to no avail.
This is how I'm trying to use it as a filter but it isn't working:
function elsm_filter_search_results_by_episode($query)
{
$query->set('post_type', ['videos']);
}
add_action(
'elementor/query/elsm_filter_search_by_episode',
'elsm_filter_search_results_by_episode'
);
I'm implementing this on Elementor int the "Custom Query Code" field of Dynamic.ooo posts widget and I got it to filter videos by episode, but I can't get the meta query to work for some reason. Therefore, what I'm trying to do here is abstract it out of those plugins and get an understanding of what I'm doing wrong in a basic functions.php context instead.
References
- https://developer.wordpress.org/reference/classes/wp_meta_query/
- https://smartwp.com/wordpress-meta_query/
- https://www.billerickson.net/code/wp_query-arguments/
- https://eventespresso.com/wiki/adding-related-events-using-advanced-custom-fields/
- https://developers.elementor.com/docs/hooks/custom-query-filter/#Using_the_Custom_Filter
Try adding
%
to themeta_value
line.'meta_value' => '"%' . get_the_title() . '%"',
As far as debugging this, there are several plugins to do so, this one is from the WordPress team: https://wordpress.org/plugins/debug-bar/