I am trying to write some code to retrieve wordpress posts to jquery using Ajax
I am just learning so have been alerting to the screen. This is what i have so far:
test.js
jQuery(document).ready(function($){
var test_name = "testname";
$.ajax({
url:'/wp-content/plugins/myPlugin/test.php',
data: {name:test_name},
type: 'POST',
cache: false,
success: function(data){
alert(data);
},
error: function(data){
alert('something went wrong');
}
});
});
test.php
<?php
$post_args = array(
'post_type' => 'products',
'numberposts' => -1
);
$myProducts = get_posts($post_args);
echo $myProducts;
?>
Can someone point me in the right direction, I can receive strings back from the test.php, so i know the test.php file is being processed. Thank you for any help/explanations
I believe I have got the solution I was looking for, thank you for pointing me towards the admin-ajax.php. Here is the code (not complete but good starter):
test.js
var wpajax_url = document.location.protocol + '//' + document.location.host + '/wp-admin/admin-ajax.php?action=myAction';
var myPostType = "products";
$.ajax({
'method':'post',
'url':wpajax_url,
'data': {aPostType: myPostType},
'datatype':'json',
'cache': false,
'success': function(data){
alert(data);
},
'error': function(data){
alert('something went wrong');
}
});
test.php
//register myAction with wordpress
add_action('wp_ajax_nopriv_myAction','myAction';
add_action('wp_ajax_myAction','myAction');
function myAction(){
$post_args = array(
'post_type' => $_POST['aPostType'],
'numberposts' => -1
);
$posts = get_posts( $post_args );
foreach ( $posts as $key => $post) {
$postArray[$key]= $post->post_title;
}
// return result as json
$json_result = json_encode( $postArray );
die( $json_result );
}
Hope this can help someone else