Customizer, change preview url when a control changes

I’ve a dropdown control that lists all pages of the website.

When I select a page in the dropdown I would update the preview iframe to that page.

There is the following method to change the customizer previewUrl

wp.customize.previewer.previewUrl( url )

But I can’t realize how and where exactly I should do this.
The dropdown control has transport set to refresh and the preview will refresh automatically everytime the control value changes.

Maybe a solution could be to change the previewUrl before the customizer automatically refresh the preview.

Do you have any suggestions to do this? Thanks in advance.

2 Answers
2

Gonna have a go… say you have a theme option themeoption[id]… instead of setting transport refresh, set it to postMessage instead, and then add this code to create a callback that first gets the page URL via AJAX then sends that back to the previewUrl as you mentioned before refreshing…

add_action('customize_preview_init,'preview_override_loader');
function preview_override_loader() {
    add_action('wp_footer','preview_override_script');
    function preview_override_script() {
        $adminajax = admin_url('admin-ajax.php');
        echo "wp.customize('themeoption[id]',function(value) {
            value.bind(function(to) {
                console.log('Posted ID: '+to); /* debug point */
                jQuery.get({url:'".$adminajax.php"', 
                    {action:'get_preview_permalink',postid:to}, 
                    function(data) {
                        if (data) {
                            console.log('Permalink: '+data); /* debug point */
                            wp.customize.previewer.previewUrl(data);
                            wp.customize.previewer.refresh();
                        }
                    } 
                });
            });
        });"
    }
}

Then just add a small AJAX function to return the permalink… this is somewhat assuming that the dropdown control is saving/posting a single numeric post ID.

add_action('wp_ajax_get_preview_permalink','get_preview_permalink');
function get_preview_permalink() {
    $postid = $_GET['postid'];
    echo get_permalink($postid);
    exit;
}

Untested crazy workaround but it seems like it might do the trick..?

Leave a Comment