You can easily populate Select, Checkbox or Radio fields with posts selected in an Advanced Custom Field (ACF) relationship field. This is accomplished using a straightforward PHP script in combination with the WordPress Filter Hook data source data source.
ACF Field Configuration
This example works with an ACF field configured as follows:
- Field Type: Relationship
- Field Label: Related Post (You can label it as anything you wish)
- Field Name:
related_post
(If your field is named differently, you’ll need to change the$acf_field_key
in the example below) - Filter by Post Type: Post
PHP Example
The code below would typically go in functions.php
of your theme (use a child theme where appropriate), or in a code snippet plugin.
When you click Get Data on the data grid in WS Form, the request will not be tied to a specific post ID. In the code snippet below, replace 123
with the ID of a test post that has some selected posts in the ACF relationship field.
// Add a filter for WordPress Filter Hook data source to use add_filter( 'wsf_acf_relationship_field', 'wsf_acf_relationship_field_hook_callback', 10, 3 ); // My callback function for tag wsf_acf_relationship_field function wsf_acf_relationship_field_hook_callback( $data_grid, $field_id, $form_object ) { // Get post ID (Set 123 to a test post ID for "Get Data" testing) global $post; $post_id = empty( $post ) ? 123 : $post->ID; // Check post ID if( empty( $post_id ) ) { return $data_grid; } // ACF field key $acf_field_key = 'related_post'; // Get relationship field (third parameter false ensures the return is not formatted) $relationship_posts = get_field( $acf_field_key, $post_id, false ); // Check field value if ( empty( $relationship_posts ) || !is_array( $relationship_posts ) ) { return $data_grid; } // Build data grid rows $rows = array(); // Look through relationship posts foreach( $relationship_posts as $relationship_post_id ) { // Add data grid row $rows[] = array( // Column data 'data' => array( // Post ID esc_attr( $relationship_post_id ), // Post title esc_html( get_the_title( $relationship_post_id ) ) ) ); } // Define columns $data_grid[ 'columns' ] = array( // Post ID array( 'label' => __( 'Post ID' ) ), // Post title array( 'label' => __( 'Post Title' ) ) ); // Define first group $data_grid[ 'groups' ] = array( array( // Label for data grid group 'label' => __( 'Related Posts' ), // Define rows in first group 'rows' => $rows ) ); return $data_grid; }