Skip to content

Instantly share code, notes, and snippets.

@nikola0203
Created October 7, 2017 10:31
Show Gist options
  • Save nikola0203/0e2e1df0b3c64244543428b1a94e9687 to your computer and use it in GitHub Desktop.
Save nikola0203/0e2e1df0b3c64244543428b1a94e9687 to your computer and use it in GitHub Desktop.
Wordpress, AJAX call, Bootsrap modal popup. AJAX function to retrieve, WooCommerce single product page, through the Bootstrap modal popup.
jQuery(document).ready(function($){
// Quick view ajax function on products page
$('.quick-view-link, .quick-view-button').on('click', function() {
var post_id = $(this).data('id');
$.ajax({
url : modal_ajax.url,
type : 'post',
data : {
post_id : post_id,
action : 'fetch_modal_content',
security : modal_ajax.nonce,
},
success : function(response) {
$('#modal').modal('show');
$('#modal_target').html(response);
}
});
});
});
/*
*
Localize script and create nonce.
*
*/
function custom_localize_scripts() {
wp_localize_script( 'custom', 'modal_ajax', array(
'url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'ajax-nonce' )
));
}
add_action( 'wp_enqueue_scripts', 'custom_localize_scripts' );
/*
*
Ajax function
*
*/
function fetch_modal_content() {
// verifies the AJAX request
check_ajax_referer( 'ajax-nonce', 'security' );
// Get post id from script
$post_id = $_POST['post_id'];
// Arguments for query
$args = array(
'p' => $post_id,
'post_type' => 'product',
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><img src="<?php echo get_template_directory_uri() . '/img/close-icon.svg' ?>"></button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-4 col-sm-offset-2">
<div class="modal-image">
<img src="<?php echo get_the_post_thumbnail_url( $post_id ); ?>">
</div>
</div>
<div class="col-sm-4">
<div id="product-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php do_action( 'woocommerce_single_product_summary' ); ?>
</div>
<div class="more-details">
<a href="<?php echo esc_url( get_permalink( $post_id ) ); ?>"><?php _e( 'View more details', 'fashion-theme' ); ?> <img src="<?php echo get_template_directory_uri() . '/img/triangle-icon.svg'; ?>"></a>
</div>
</div>
</div>
</div>
<?php
endwhile;
endif;
wp_reset_postdata();
die();
}
add_action( 'wp_ajax_fetch_modal_content', 'fetch_modal_content' );
add_action( 'wp_ajax_nopriv_fetch_modal_content', 'fetch_modal_content' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment