Save CPTUI settings data to file

If you ever find need to save your Custom Post Type UI settings data to a file, on top of to the database like normal, the following snippet should help you out.

This will be particularly useful if you find need to version control the settings, as databases aren’t easy to version control themselves.

<?php
/**
 * Saves post type and taxonomy data to JSON files in the theme directory.
 *
 * @param array $data Array of post type data that was just saved.
 */
function pluginize_local_cptui_data( $data = array() ) {
    $theme_dir = get_stylesheet_directory();
    // Create our directory if it doesn't exist.
    if ( ! is_dir( $theme_dir .= '/cptui_data' ) ) {
        mkdir( $theme_dir, 0755 );
    }

    if ( array_key_exists( 'cpt_custom_post_type', $data ) ) {
        // Fetch all of our post types and encode into JSON.
        $cptui_post_types = get_option( 'cptui_post_types', array() );
        $content = json_encode( $cptui_post_types );
        // Save the encoded JSON to a primary file holding all of them.
        file_put_contents( $theme_dir . '/cptui_post_type_data.json', $content );
    }

    if ( array_key_exists( 'cpt_custom_tax', $data ) ) {
        // Fetch all of our taxonomies and encode into JSON.
        $cptui_taxonomies = get_option( 'cptui_taxonomies', array() );
        $content = json_encode( $cptui_taxonomies );
        // Save the encoded JSON to a primary file holding all of them.
        file_put_contents( $theme_dir . '/cptui_taxonomy_data.json', $content );
    }
}
add_action( 'cptui_after_update_post_type', 'pluginize_local_cptui_data' );
add_action( 'cptui_after_update_taxonomy', 'pluginize_local_cptui_data' );

What the snippet essentially does is create a directory in your active theme, if it does not already exist. Then, it checks if a post type or a taxonomy is being saved. Depending on which object type is saved, the code fetches the appropriate complete option from the database, encodes it into JSON, and writes to a file inside the provided directory.

All of this happens on the “cptui_after_update_$object” hooks. Despite how they sound, they are run on both new and existing items being saved.

For loading and dynamically reading the content from these files, check out Load CPTUI Settings Data From File

Updated Dec 12, 2022 9:10 PM