I'm trying to query a post type (intervention) via a post object field (intervention_country) by the title (of the related custom post type - country).
Something like:
$wp_query = new WP_Query();
$wp_query->query( array (
'post_type' => 'intervention',
'meta_query' => array(
array(
'key' => 'intervention_country',
'value' => 'country_selected',
'compare' => '=='
)
)
));
Can this be done? From other questions it looks like I have to give an ID but I would like to query using the title of the CPT (country) instead as given by `'country_selected' above
I'm trying to query a post type (intervention) via a post object field (intervention_country) by the title (of the related custom post type - country).
Something like:
$wp_query = new WP_Query();
$wp_query->query( array (
'post_type' => 'intervention',
'meta_query' => array(
array(
'key' => 'intervention_country',
'value' => 'country_selected',
'compare' => '=='
)
)
));
Can this be done? From other questions it looks like I have to give an ID but I would like to query using the title of the CPT (country) instead as given by `'country_selected' above
It can be done, but it won't be so easy. Post Object is stored as an ID, so you can't use meta query to search by post title in such case... There are few ways of solving that problem:
acf/save_post
action to save title of given post object as another meta value:// Add this to your functions.php
function save_intervention_country_name ( $post_id ) {
$country_id = get_field( 'intervention_country', $post_id );
if ( $country_id ) {
update_post_meta( $post_id, 'intervention_country_name', get_post_field( 'post_title', $country_id ) );
}
}
add_action( 'acf/save_post', 'save_intervention_country_name', 20 );
And then you can search using intervention_country_name
field:
$wp_query->query( array (
'post_type' => 'intervention',
'meta_query' => array(
array(
'key' => 'intervention_country_name',
'value' => <COUNTRY NAME>,
'compare' => '=='
)
)
));
posts_where
and posts_join
filters to modify SQL query.You'll have to add a JOIN statement to join your post object field with posts table, and then add where searching by title.
So if there is a select field, then fill its values with IDs. Or if you can't do that, you always can get the country first and then use its ID:
$country = get_page_by_title( <COUNTRY_NAME>, OBJECT, <COUNTRY_POST_TYPE> );
if ( $country ) {
$wp_query->query( array (
'post_type' => 'intervention',
'meta_query' => array(
array(
'key' => 'intervention_country',
'value' => $country->ID,
'compare' => '=='
)
)
));
}