Last active
November 23, 2019 17:02
-
-
Save ChaseWiseman/ad12912f42b9418718f4 to your computer and use it in GitHub Desktop.
Load modals as WordPress template parts via AJAX
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
$( function() { | |
var loadModal = function( modal ) { | |
$.post( | |
pinwheel_modals.ajax_url, | |
{ | |
action: 'load_modal', | |
modal: modal | |
}, | |
/* Handle the response! */ | |
function ( response ) { | |
if ( 0 != response ) { | |
modal = $.parseHTML( response ); | |
/* Add the modal to the body. */ | |
$( 'body' ).append( modal ); | |
/* Take various actions when the modal is added. */ | |
$( modal ).addClass( 'modal-show' ); | |
$( 'body' ).addClass( 'has-modal' ); | |
} | |
} | |
); | |
} | |
} ); |
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
/** | |
* Load a requested modal via AJAX. | |
* | |
* @since 1.0.0 | |
* | |
* @return void | |
*/ | |
function pinwheel_ajax_load_modal() { | |
ob_start(); | |
get_template_part( 'parts/modal', $_POST['modal'] ); | |
$modal = ob_get_clean(); | |
if ( $modal ) { | |
echo $modal; | |
} else { | |
echo 0; | |
} | |
die(); | |
} | |
add_action( 'wp_ajax_load_modal', 'pinwheel_ajax_load_modal' ); | |
add_action( 'wp_ajax_nopriv_load_modal', 'pinwheel_ajax_load_modal' ); |
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
/* Load a modal when any element with a modal specified is clicked */ | |
$( '[data-modal]' ).on( 'click', function( e ) { | |
e.preventDefault(); | |
var modal = $( this ).data( 'modal' ); | |
loadModal( modal ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I get this error: pinwheel_modals :(