Support

Account

Home Forums Add-ons Flexible Content Field Copy Flexible Content Layout From One Post to Another Reply To: Copy Flexible Content Layout From One Post to Another

  • To answer my own question, here’s an example of how I achieved it with a Select field, Flexible Content field, and a function that runs on acf/save_post:

    
    function import_layouts_from_a_different_page( $post_id ) {
    
    	// Bail early if no ACF data
    	if ( empty( $_POST['acf'] ) ) {
    		return;
    	}
    
    	// Flex layouts from this page (field_56381b4c8e557 is a Flexible Content field named "Layouts")
    	if ( is_array( $_POST['acf']['field_56381b4c8e557'] ) && ! empty( $_POST['acf']['field_56381b4c8e557'] ) ) {
    		$current_page_flex_layouts = $_POST['acf']['field_56381b4c8e557'];
    	} else {
    		$current_page_flex_layouts = array();
    	}
    
    	// Determine if there are any pages to import (field_57924308049be is a Select field named "import_flex_layout")
    	$pages_to_import = $_POST['acf']['field_57924308049be'];
    
    	// If there aren't any layouts to import, skip the rest.
    	if ( empty( $pages_to_import ) ) {
    		return;
    	}
    
    	// Loop through the (possibly) multiple pages that we'll import.
    	foreach ( $pages_to_import as $page_id ) {
    
    		// Get the layouts value from the selected page.
    		$layouts_from_page = get_field_object( 'layouts', $page_id, false, true );
    
    		// Add the value to this page.
    		if ( ! empty( $layouts_from_page['value'] ) ) {
    			$current_page_flex_layouts = array_merge( $current_page_flex_layouts, $layouts_from_page['value'] );
    		}
    	}
    
    	// Re-set the Layout field value with any imported pages, then continue saving.
    	$_POST['acf']['field_56381b4c8e557'] = $current_page_flex_layouts;
    
    	// Clear out the pages to import setting
    	$_POST['acf']['field_57924308049be'] = array();
    
    }
    
    // run before ACF saves the $_POST['acf'] data
    add_action( 'acf/save_post', 'import_layouts_from_a_different_page', 1 );