Skip to content

Instantly share code, notes, and snippets.

@Wadizorg
Created April 4, 2018 00:16
Show Gist options
  • Save Wadizorg/0f3ec80d27aea12003134fcc1fe72dc4 to your computer and use it in GitHub Desktop.
Save Wadizorg/0f3ec80d27aea12003134fcc1fe72dc4 to your computer and use it in GitHub Desktop.
AJAX functionality for WordPress themes
function fetch_modal_content() {
if ( isset($_REQUEST) ) {
$post_id = $_REQUEST['id'];
?>
<div class="modal-body">
<h1><?php echo get_the_title($post_id); ?></h1>
<?php echo wpautop(get_the_content($post_id)); ?>
</div>
<?php
}
die();
}
add_action( 'wp_ajax_fetch_modal_content', 'fetch_modal_content' );
add_action( 'wp_ajax_nopriv_fetch_modal_content', 'fetch_modal_content' );
<!-- Assumes that you're using Bootstrap -->
<button id="button" data-id="23">Load Modal</button>
<div id="modal" class="modal fade">
<div class="modal-dialog">
<div id="modal_target" class="modal-content">
</div>
</div>
</div>
// Assumes that you're using jQuery and Bootstrap
// The `ajaxurl` variable, should be declared in
// header.php like so:
// ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var $button = $('#button');
var $modal = $('#modal');
var $modal_target = $('#modal_target');
$button.click(function() {
var id = $(this).data('id');
$.ajax({
url: ajaxurl,
data: {
'action' : 'fetch_modal_content',
'id' : id
},
success:function(data) {
$modal_target.html(data);
$modal.modal('show');
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment