Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to create a filter to add acf fields from relationship within a repeater, on a custom endpoint. #101

Closed
akhanukov opened this issue Feb 5, 2017 · 13 comments
Labels

Comments

@akhanukov
Copy link

Hi @airesvsg, I've looked through all of the issues and see that you send everyone to Issue #9 and the resolution there. I've tried all instances and different combinations and I still can't get it to work, it being a relationship field, within a repeater, on a custom endpoint. Perhaps the issue in my case is that my endpoint isn't just a custom post type, but actually a combination of a custom class controller that replaces/extends WP_REST_Posts_Controller with some logic that queries one custom post type for data in an ACF field and then filters another custom post type based on if that field or data exists. Finally, it is called but a custom query variable. So my url is:

/wp-json/wp/v2/messages_in_interaction/?interactionID=6800 and the output is:

acftorestapi-issue9-customcontroller

As you'll see, I circled where I would like ACF fields to display. Note, that because I'm using the custom classes, /messages nor /interactions endpoints on their own don't work, yet display as linked data in the API. Any ideas? Thanks!

@airesvsg
Copy link
Owner

airesvsg commented Feb 6, 2017

Hi @akhanukov,
please try it:

add_filter( 'acf/rest_api/messages_in_interaction/get_fields', function( $data, $request, $response ) {
  if ( $response instanceof WP_REST_Response ) {
      $data = $response->get_data();
  }

  if ( isset( $data['acf']['attachments'] ) && ! empty( $data['acf']['attachments'] ) ) {
    foreach ( $data['acf']['attachments'] as &$a ) {
      if ( isset( $a['content_items'] ) && ! empty( $a['content_items'] ) ) {
        foreach ( $a['content_items'] as &$c ) {
          $c['acf'] = get_fields( $c['ID'] );
        }
      }
    }
  }   

  return $data;
}, 10, 3 );

Thanks

@akhanukov
Copy link
Author

Thank you for the fast response @airesvsg! I will try it shortly and let you know how it worked!

@akhanukov
Copy link
Author

akhanukov commented Feb 6, 2017

Hi @airesvsg, unfortunately, it's not working, unless I'm implementing it wrong. Is there any way I can help debug? I'm going to post my functions that set up this custom endpoint, in case that helps, since I think that perhaps the custom query variable might be messing something up. Though, I did also try without the query variable (/wp-json/wp/v2/messages_in_interaction/) in which I get a list of all messages and still, I could not see the sub-acf fields either.

            // Extend the `WP_REST_Posts_Controller` class with 'Messages_Interaction_Controller'
            class Messages_Interaction_Controller extends WP_REST_Posts_Controller
            {
                // Override the register_routes() and add '/messages_in_interaction'
                public function register_routes()
                {
                    // (?P<id>[\d]+)
                    register_rest_route($this->namespace, '/messages_in_interaction', [
                        [
                            'methods' => WP_REST_Server::READABLE,
                            'callback' => [$this, 'get_items'],
                            //'callback' => 'get_post_title_by_author',
                            'permission_callback' => [$this, 'get_items_permissions_check'],
                            'args' => $this->get_collection_params(),
                        ],
                        'schema' => [$this, 'get_public_item_schema'],
                    ]);
                }

                // Override the `prepare_items_query` method in order to add custom query arguments
                protected function prepare_items_query($prepared_args = [], $request = null)
                {
                    //global $cpt_onomy;
                    global $post;
                    // Call the parent class method
                    $query_args = parent::prepare_items_query($prepared_args, $request);

                    $posts = get_posts(array(
                        'post_type' => 'message',
                        'meta_query' => array(
                            array(
                                'key' => 'tsm_messages', // name of custom field
                                'value' => '"' . $_GET['interactionID'] . '"', // matches exaclty "123", not just 123. This prevents a match for "1234"
                                'compare' => 'LIKE'
                            )
                        ),
                        'posts_per_page' => 100,
                    ));

                    //print_r($posts);

                    foreach ( $posts as $post ) :
                        setup_postdata( $post ); 
                        $id = get_the_ID();
                        $ITarray[] = $id;https://www.advancedcustomfields.com/resources/get_row_layout/
                    endforeach; 
                    wp_reset_postdata();


                    //$objects = $cpt_onomy->get_objects_in_term( $_GET['interactionID'], 'interaction' );
                    // Extend custom query arguments
                    $custom_query_args = [
                    'post_type' => 'message',
               			'post__in' => $ITarray,
               			'orderby' => 'menu_order',
               			'order' => 'ASC',
               			'posts_per_page' => 100,
                    ];

                    // Return a merged array including default and custom arguments
                    return array_merge($query_args, $custom_query_args);
                }

            }

            // Create an instance of `Messages_Interaction_Controller` and call register_routes() methods
            add_action('rest_api_init', function () {
                $myProductController = new Messages_Interaction_Controller('message');
                $myProductController->register_routes();
            });

@akhanukov
Copy link
Author

Hi @airesvsg, just sending a reminder to the above post. If there's any way to help me help debug this further, I would appreciate it! Thank you for your help!

@akhanukov
Copy link
Author

Hi @airesvsg, sorry to keep bugging you. I've been trying to make this work without much success. Any hints on other things to try? I can try to rebuild the original custom endpoint if that would help. Thanks!

@airesvsg
Copy link
Owner

Hi @akhanukov,
Please, send me your files and database for my email (airesvsg@gmail.com).
Thanks

@akhanukov
Copy link
Author

I'm unable to send everything like that due to it being somewhat proprietary, but I will gladly send you screenshots of tables and some code. Thank you!

@airesvsg
Copy link
Owner

Ok, try it:

// rest_{post_type}_query
add_filter( 'rest_messages_query', function( $args, $request ) {
  $interaction = $request->get_param( 'interaction' );
  if ( ! is_null( $interaction ) ) {
    $args['meta_query'] = array(
      array(
        'key'     => 'content_items_%_content_items',
        'compare' => '=',
        'value'   => (int) $interaction,
      )
    );
  }
  return $args;
}, 10, 2 );

add_filter( 'posts_where', function( $where ) {
  return str_replace( "meta_key = 'content_items_%", "meta_key LIKE 'content_items_%", $where );
} );

URL: http://mysite.com/wp-json/wp/v2/messages_in_interaction/?interaction=1234

Thanks

@akhanukov
Copy link
Author

Hey @airesvsg! Thanks for giving it another try. I truly appreciate your plugin and time and efforts outside of it to help me make this work. Unfortunately, I tried adding this code (with interaction as well as interactionID for get_param) and I still can't get [n].acf.attachments[n].content_items[n].ID to work. :( I wanted to clarify that this code is in addition to the code above with the acf filter or a replacement of? In either case I tried both cases as well. I wish there was a way I could help debug this, but I can only find ways to break the filter, not get into the variables being passed around or monitor where there may be an error. Let me know if there is any way I can. In the meantime, I am trying to get the materials together based on your request. Thanks again for trying.

@akhanukov
Copy link
Author

Hi @airesvsg, I'm still struggling trying to make this work. I still have to send you the files, but is there any simple way to debug filters like this? I found some helpful tools, but they are "within" wordpress's template structure, not in the output of an API. Thanks!

@airesvsg
Copy link
Owner

Hi @akhanukov,
Please, send me the files, this is the most easy way to solve the problem.
Email: airesvsg@gmail.com
Thanks

@akhanukov
Copy link
Author

Hi @airesvsg, after taking a break from this and coming back to see post Post 109, and again trying to implement the filter, I'm convinced that the issue is that messages_in_interaction is not a custom post type, but a filtering of custom post type messages by whether they're associated with an interaction, as you can see in the code above. All of documentation in this project's readme and the filter we're using here, all reference {type} or {post-type}.

My hunch is that since messages_in_interaction isn't a post type, the filter doesn't actually do anything. Also, because of the custom endpoint, my normal wp-json routes don't have a messages either, however, there does exist a /acf/v3/messages/. I guess I just want to make sure that's not really the issue this whole time. Thoughts? Thanks for your help!

@akhanukov
Copy link
Author

Hi @airesvsg, should I open this as a separate ticket?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants