Home Forums ACF PRO Ajax / Filter Relationship Field


Ajax / Filter Relationship Field

  • I’m trying to filter a relationship field based on the value of a post object select field.

    To test the ajax, I’m using:

    //-- JS
    $( '#acf-field_571a7d26c9700-input' ).on( 'change', function() {
      // getting the post object select value
      var po_select = $(this).val();
      var data = {
         'action': 'my_ajax',
         'data': po_select
      $.post(ajaxurl, data, function(response) {
        console.log( po_select );
    //-- Function
    function my_ajax() {
      // testing the ajax by saving the value in a simple text 'test' field; this works!
      $field_key = 'field_571a931c167c7';
      $value = $_POST['data'];
      update_field( $field_key, $value, 'option' );
    add_action( 'wp_ajax_my_ajax', __NAMESPACE__ . '\\my_ajax' );
    add_action( 'wp_ajax_nopriv_my_ajax', __NAMESPACE__ . '\\my_ajax' );

    I think acf/fields/relationship/query will be used to filter the relationship field. However, I’m not sure how to combine this with the ajax. I can successfully filter the field by using:

    function my_relationship_query( $args, $field, $post ){
      $args['meta_query'] = array(
          'key'     => 'custom_acf_field',
          'value'   => '"###"', // the value will be po_select
          'compare' => 'LIKE'
      $post = 'field_571a931c167c7';
      $post = 'option';
      return $args;
    add_filter('acf/fields/relationship/query', __NAMESPACE__ . '\\my_relationship_query', 10, 3);

    Can someone help? Thanks!

  • Hi @aisforadam

    If you’re able to save the value, I believe you can get the value in the “acf/fields/relationship/query” hook like this:

    $args['meta_query'] = array(
          'key'     => 'custom_acf_field',
          'value'   => get_field("custom_field_name", "option"),
          'compare' => 'LIKE'

    You can also save it as the current post/page custom field by providing the ID instead of “option” for the update_field() and get_field() functions.

    I hope this helps.

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

The topic ‘Ajax / Filter Relationship Field’ is closed to new replies.