Skip to content

Instantly share code, notes, and snippets.

@ChaseWiseman
Last active November 23, 2019 17:02
Show Gist options
  • Save ChaseWiseman/ad12912f42b9418718f4 to your computer and use it in GitHub Desktop.
Save ChaseWiseman/ad12912f42b9418718f4 to your computer and use it in GitHub Desktop.
Load modals as WordPress template parts via AJAX
$( 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' );
}
}
);
}
} );
/**
* 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' );
/* 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 );
} );
@AtRaoN
Copy link

AtRaoN commented Nov 23, 2019

Modals are not showing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment