Skip to content

Instantly share code, notes, and snippets.

@PauliusKrutkis
Last active March 7, 2017 20:53
Show Gist options
  • Save PauliusKrutkis/6d637e20adcee29bdd8db615078d8c26 to your computer and use it in GitHub Desktop.
Save PauliusKrutkis/6d637e20adcee29bdd8db615078d8c26 to your computer and use it in GitHub Desktop.
Wordpress ajax response snippet
<?php
function getPosts()
{
$args = [
'post_type' => 'post',
'posts_per_page' => 5,
'paged' => $_GET['page'],
];
if ($_GET['category']) {
$args['category_name'] = $_GET['category'];
}
$query = new WP_Query($args);
while ($query->have_posts()) {
$query->the_post();
$posts[] = [
'id' => get_the_ID(),
'title' => get_the_Title(),
'excerpt' => get_the_excerpt(),
'link' => get_the_permalink(),
'time' => get_the_time('Y m d'),
];
}
$pages = $query->max_num_pages;
$data = array(
'posts' => $posts,
'pages' => $pages,
);
header("Content-type: application/json");
echo json_encode($data);
die;
}
add_action('wp_ajax_getPosts', 'getPosts');
add_action('wp_ajax_nopriv_getPosts', 'getPosts');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment