Apply `the_content’ filter to theme customisation live preview

I’ve again been looking in to this so I’ve decided to post an answer because I actually have done this using an AJAX call.

As pointed out in the comments to my question by @Otto

The point of postMessage is that it’s sending data directly, in the browser. It’s not going through the server, so no, you cannot apply PHP filters to it unless it’s using refresh.”

So using the original example from above for context, you could apply filters to text updated via the postMessage method using an AJAX call as follows –

JS in your theme-customiser.js file –

(function($){

    /** Update the footer text */
    wp.customize('footer_text', function(value){
        value.bind(function(newval){

            var data = {
                action: 'filter_using_the_content',
                text:   newval
            }

            $.post(MyAjax.ajaxurl, data, function(response){
                $('#footer-left').html(response);
            });

        });
    });

})(jQuery);

PHP in your functions.php file –

add_action('wp_ajax_filter_using_the_content', 'my_filter_using_the_content');
function my_filter_using_the_content(){

    echo apply_filters('the_content', $_POST['text']);
    die();  // Required for a proper result

}