Categories
How To

Saving Theme Data to a File

Including HTML content from WordPress when it’s not your post content but your theme settings can be done! It’s just a mess.

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 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.

<?php
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();

Top ↑

The Javascript 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.

<script>
	var elem = document.getElementById("wpcontent");

fetch('https://example.com/wp-content/top-bar.html', {
        credentials: 'include'
    })
        .then(function (response) {
            return response.text();
        })
        .then(function (text) {
            console.log('Request successful', text.length);
			console.log('Request successful2', text);
			$('.wpcontent').html(text);
        })
        .catch(function (error) {
            console.log('Request failed', error)
        });
</script>

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

And magic happens.