Saving Theme Data to a File

Your life isn’t all WordPress.

I know, I know, I said a dirty thing, but let’s be honest, everything isn’t always all WordPress. And when that happens, you have to do some weird things to make your data shared.

One of the things I needed one day was a way for non-WordPress files to get access to a theme setting. See, the theme let me set a top-bar and customize it. Sometimes I did that to share news, sometimes to link to latest posts. Regardless, I updated it via Customizer, and it worked great for WordPress.

Not so much for my static HTML site, or my non-WordPress PHP site.

I dwelled on it for a while and then thought “Wait, if the theme knows how to echo a specific setting, then there has to be a function for that. And if there’s a function, then can’t I hook into Customizer saving to trigger the creation of an HTML file with the data and call that from my other sites?”

And guess what? You can!

The WordPress Code

Toss this in an MU Plugin and it’ll save a file to wp-content/top-bar.html when you save customizer settings.

class HELF_Top_Bar {

	public function __construct() {
		add_action( 'customize_save_after', array( $this, 'save_top_file' ) );

	 * Safe the top file
	 * When customizer is saved, copy the get_theme_mod() data and parse it
	 * into a file: wp-content/top-bar.html
	 * @return n/a
	public function save_top_file() {
		$default     = 'Something Default Here';
		$banner_text = get_theme_mod( 'top-banner-text', $default );

		$fp = fopen( WP_CONTENT_DIR . '/top-bar.html', 'w' );
		fwrite( $fp, $banner_text );
		fclose( $fp );



new HELF_Top_Bar();

The Javascript

The what?

For my other PHP file, it’s a simple file_get_contents() call to the HTML. But for static HTML I had to resort to trickery with Javascript.

	var elem = document.getElementById("wpcontent");

fetch('', {
        credentials: 'include'
        .then(function (response) {
            return response.text();
        .then(function (text) {
            console.log('Request successful', text.length);
			console.log('Request successful2', text);
        .catch(function (error) {
            console.log('Request failed', error)

<div class="wpcontent"></div>

And magic happens.




%d bloggers like this: