Last active
November 15, 2017 17:14
-
-
Save mcfarhat/d5d303e3ecd7ac101c566065d604464b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<?php | |
//hooks required to perform the connection between AJAX calls and php function | |
add_action( 'wp_ajax_nopriv_filter_matching_cpts', 'filter_matching_cpts' ); | |
add_action( 'wp_ajax_filter_matching_cpts', 'filter_matching_cpts' ); | |
/* function handling the generation and response back to the AJAX call/front end | |
function filter_matching_cpts(){ | |
//perform a query to grab the instances of the custom post type | |
$args = array( | |
'post_type' => 'cpt', | |
'post_status' => 'publish', | |
'posts_per_page' => -1 | |
); | |
$loop = new WP_Query( $args ); | |
$cpt_array = array(); | |
//loop through the results | |
while ( $loop->have_posts() ) : $loop->the_post(); | |
$cpt_array[] = array( | |
'title' => $loop->post->post_title, | |
'meta_data' => get_post_meta($loop->post->ID), | |
); | |
endwhile; | |
wp_reset_query(); | |
//encode the data into a format acceptable by JS | |
echo json_encode($cpt_array); | |
//kill the process to return properly without additional 0 | |
die(); | |
} | |
//enqueue ajax url | |
function gk_cstm_enqueue() { | |
wp_localize_script( 'ajax-script', gk_cstm_calc', | |
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); | |
} | |
add_action( 'wp_enqueue_scripts', 'gk_cstm_enqueue' ); | |
?> | |
<script> | |
var mortgage_plans; | |
//perform the AJAX call | |
jQuery(document).ready(function($){ | |
$.ajax({ | |
type: "POST", | |
dataType: "json", | |
url: gk_cstm_calc.ajax_url, | |
custom_data: 'custom_data', | |
data: { | |
'action' : 'filter_matching_cpts', | |
'custom_data' : custom_data, | |
}, | |
success: function(data){ | |
//perform action on received data | |
console.log(data); | |
mortgage_plans = data; | |
jQuery.each(mortgage_plans, function(index, plan){ | |
//do some action here | |
console.log(data['title']); | |
} | |
//or simply render the content into an HTML field | |
jQuery('#data_content').empty().html(data); | |
} | |
}); | |
}); | |
</script> | |
<html> | |
<body> | |
<div id="data_content"> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment