Skip to content

Instantly share code, notes, and snippets.

@moskalukigor
Last active September 14, 2017 08:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save moskalukigor/544cc7cd0a046c2c8014a37cc79c690c to your computer and use it in GitHub Desktop.
Save moskalukigor/544cc7cd0a046c2c8014a37cc79c690c to your computer and use it in GitHub Desktop.
Wordpress Ajax
<?php
/*IS NOT WOOCOMMERCE*/
if ( ! function_exists( 'is_ajax' ) ) {
/**
* is_ajax - Returns true when the page is loaded via ajax.
* @return bool
*/
function is_ajax() {
return defined( 'DOING_AJAX' );
}
}
//FUNCTIONS AJAX
add_action( 'wp_ajax_loadPosts', 'loadPosts');
add_action( 'wp_ajax_nopriv_loadPosts', 'loadPosts');
function loadPosts($paged = 1){
extract($_POST);
//show post
if (is_ajax()) {
exit();
}
}
//FUNCTIONS VARIABLES JS
function js_variables(){
$variables = array (
'ajax_url' => admin_url('admin-ajax.php'),
);
echo(
'<script type="text/javascript">window.wp_data = '.
json_encode($variables).
';</script>'
);
}
add_action('wp_head','js_variables');
$(document).on("click", "#button", function(){
var ajaxcontent = $('.products');
$.ajax({
type: 'POST',
url: window.wp_data.ajax_url,
data: {
action: "loadPosts",
},
success: function (html) {
ajaxcontent.html(html);
}
});
return false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment