I am a beginner in php and wordpress. I try to make a simple plugin which can show 3 latest post and show them in the page. At first I want to get an array which has been already encoded in json, and then work with with js. But somewhere in the code I have a mistake or maybe I don't understand something important. There is my code which return nothing. If delete dataType in Ajax, will return whole code. Any advises will be appreciated. JS and PHP in one file.
<button onclick='myAjax()'>Button</button>
<script type="text/javascript">
function myAjax(){
$.ajax({
type: "GET",
url: "plug_in.php",
data: {action: "call_this"},
dataType: 'json',
success:function(data){
alert(data);
}
})
};
</script>
<?
//Plugin name: My plagin
//Description: This plugin for getting posts and posts they
function show_post(){
$args = array(
'numberposts' => 3
);
$post = get_posts($args);
$all_post = array();
foreach ($post as $key) {
array_push($all_post, $key->post_author,$key>post_title,$key>post_content,
$key->post_date);
}
echo json_encode($all_post);
};
if($_GET['action'] == 'call_this'){
show_post();
};
?>
try this code
function show_post(){
$args = array('numberposts' => 3);
$post = get_posts($args);
$all_post = array();
foreach ($post as $key) {
array_push($all_post, $key->post_author,$key-`enter code here`>post_title,$key>post_content,
$key->post_date);
}
echo json_encode($all_post);
}
if($_GET['action'] == 'call_this'){
show_post();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.