-
-
Save westonruter/1095096e6bca16744421952a4da498c6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: WPSE 282139 | |
* Plugin URI: https://wordpress.stackexchange.com/questions/282139/how-to-make-get-theme-mod-work-with-ajax-in-the-customizer-preview | |
*/ | |
add_action( 'wp_ajax_my_request', function () { | |
ob_start(); | |
echo get_theme_mod( 'position', 'top' ); | |
wp_send_json_success( ob_get_clean() ); | |
wp_die(); | |
} ); | |
add_action( 'wp_enqueue_scripts', function() { | |
wp_enqueue_script( | |
'my-request', | |
plugin_dir_url( __FILE__ ) . 'request.js', | |
array( 'jquery' ), | |
null, | |
true | |
); | |
wp_localize_script( | |
'my-request', | |
'myArgs', | |
array( | |
'url' => admin_url( 'admin-ajax.php' ), | |
'action' => 'my_request', | |
) | |
); | |
} ); | |
add_action( 'customize_register', function( WP_Customize_Manager $wp_customize ) { | |
$wp_customize->add_section( 'position', array( | |
'title' => 'Position', | |
'priority' => 1, | |
) ); | |
$wp_customize->add_setting( 'position', array( | |
'default' => 'top', | |
) ); | |
$wp_customize->add_control( 'position', array( | |
'label' => 'position', | |
'section' => 'position', | |
'type' => 'select', | |
'choices' => array( | |
'top' => 'Top', | |
'right' => 'Right', | |
'bottom' => 'Bottom', | |
'left' => 'Left', | |
), | |
) ); | |
} ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* global myArgs, console, _wpCustomizeSettings */ | |
(function( jQuery ) { | |
'use strict'; | |
var data = { | |
action: myArgs.action | |
}; | |
function request() { | |
var url = myArgs.url, urlParser; | |
// Workaround defect introduced in WordPress 4.8.2 where preview nonce is not included in request. | |
if ( 'undefined' !== typeof _wpCustomizeSettings ) { | |
urlParser = document.createElement( 'a' ); | |
urlParser.href = url; | |
urlParser.search += '&customize_preview_nonce=' + _wpCustomizeSettings.nonce.preview; | |
url = urlParser.href; | |
} | |
jQuery.post( url, data, function( response ) { | |
console.log( response ); | |
} ); | |
} | |
document.addEventListener( 'DOMContentLoaded', function() { | |
request(); | |
} ); | |
})( jQuery ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment