Support

Account

Home Forums ACF PRO Relationship field – set all values as selected as default

Helping

Relationship field – set all values as selected as default

  • Hi

    Is there a way to have a “Relationship” field set all its values as selected/added, when a page is created in the backend?

    So that the user don’t have to choose manually.

    Cheers
    Kris

  • I’m sure there are more eloquent ways to pull this off however give this a try. This will only work on relationship fields which are pulling in choices from custom post types.

    function my_acf_load_value( $value, $post_id, $field ) {
    
    	// Loads current post
    	$post = get_post( $post_id );
    
    	// Check we are on the new screen
    	if ( $post->post_status == 'auto-draft' ) {
    
    		// Pull in custom post types from fields
    		$post_types = $field['post_type'];
    
    		// Fetches all post IDs choices
    		$post_ids = get_posts(
    			array(
    				'post_type'      => $post_types,
    				'posts_per_page' => '-1',
    				'fields'         => 'ids',
    			)
    		);
    
    		// Assign all choices as the default value
    		$value = $post_ids;
    
    	}
    
    	return $value;
    }
    
    add_filter( 'acf/load_value/type=relationship', 'my_acf_load_value', 10, 3 );
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Relationship field – set all values as selected as default’ is closed to new replies.