Add a preview to a WordPress Control Panel

If you look at Mystique theme (a great example of option panel with preview BTW) you can see that the main idea is to lavrage the form fields OnChange or change() events to load the theme’s preview with Jquery and a bit of ajax.

So you have one function to load by ajax the preview

function mystique_get_site_preview() {
  check_ajax_referer("site_preview"); ?>
  <iframe id="themepreview" name="themepreview" src="https://wordpress.stackexchange.com/questions/12679/<?php echo get_option("home'); ?>/?preview=1"></iframe>
  <?php die();
}

and to create the auto preview effect you use some JQuery with PHP:

$nonce = wp_create_nonce('site_preview');
?>
<script type="text/javascript">
    jQuery(document).ready(function () {
        jQuery("#$zona1y").change(function() {// if a user changed the y-Axis
            check_preview_refresh();
            }
        );
        jQuery("#$zona1x").change(function() {// if a user changed the x-Axis
            check_preview_refresh();
            }
        );
    });

    function check_preview_refresh(){
        if (jQuery("#zona1y").val() != '' && jQuery("#zona1x").val() != '' ){
            jQuery.ajax({
                type: "post",url: "admin-ajax.php",data: { action: 'site_preview', _ajax_nonce: '<?php echo $nonce; ?>' },
                success: function(html){
                    jQuery("#themepreview").html(html);
                    jQuery("#themepreview").show();
                }
            });
        }
    }
</script>

Now this code assumes that you have two input fields with the id of “zona1y” and “zona1y”
and a div wrapping your Iframe with the id of “themepreview”.

and that should get you started.

Update:

I forgot you will need to add:

add_action('wp_ajax_site_preview', 'mystique_get_site_preview');

Now

the first part + the last line of code go in your functions.php

and the second part needs to go on your theme option panel page.

Leave a Comment