Support

Account

Home Forums ACF PRO ACF Post Object meta-query by title not ID

Helping

ACF Post Object meta-query by title not ID

  • 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.

  • You cannot do a query using the title of the related post. This information is not stored, only the post ID is. It is possible if you copy the title of the related post and store it with the posts you want to search. Something like

    
    add_filter('acf/save_post', 'copy_country_title', 20);
    function copy_country_title($post_id) {
      // get the value of the country field
      $country_id = get_field('intervention_country', $post_id);
      $country_title = get_the_title($country_id);
      // now store this value in a new meta field
      update_post_meta($post_id, 'intervention_country_title', $country_title);
    }
    

    then you can use the new field intervention_country_title for your query

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.