Load CPTUI Settings Data From File

In Save CPTUI settings data to file we showed how to automatically save post type and taxonomy data to a local file stored in your active theme, every time you save a post type or taxonomy.

However, we never showed how to potentially load those data files and let that data handle the registration of content types. When the documentation post was originally written, the functionality to properly import was not in place. Since then, Custom Post Type UI (CPTUI) has evolved and we have the ability to successfully pull the data back in.

Below are some useful functions and callbacks to read and import local JSON files and pass them into the CPTUI registration process.

/**
 * Load local post type JSON data.
 *
 * @return string $value overriding content for CPTUI
 */
function pluginize_load_local_cptui_post_type_data( $data ) {

	$loaded = pluginize_load_local_cptui_data( 'cptui_post_type_data.json' );

	if ( false === $loaded ) {
		return $data;
	}

	$data_new = json_decode( $loaded, true );

	if ( $data_new ) {
		return $data_new;
	}

	return $data;
}
add_filter( 'cptui_post_types_override', 'pluginize_load_local_cptui_post_type_data' );

/**
 * Load local taxonomy JSON data.
 *
 * @return string $value overriding content for CPTUI
 */
function pluginize_load_local_cptui_taxonomies_data( $data ) {
	$loaded = pluginize_load_local_cptui_data( 'cptui_taxonomy_data.json' );

	if ( false === $loaded ) {
		return $data;
	}

	$data_new = json_decode( $loaded, true );

	if ( $data_new ) {
		return $data_new;
	}

	return $data;
}
add_filter( 'cptui_taxonomies_override', 'pluginize_load_local_cptui_taxonomies_data' );

/**
 * Helper function to load a specific file.
 * @param string $file_name Name of the local JSON file.
 *
 * @return false|string
 */
function pluginize_load_local_cptui_data( $file_name = '' ) {
	if ( empty( $file_name ) ) {
		return false;
	}
	$theme_dir = get_stylesheet_directory() . '/cptui_data';
	$path      = $theme_dir . '/' . $file_name;

	return file_get_contents( $path );
}
Updated Dec 9, 2022 8:41 PM