Skip to content

Instantly share code, notes, and snippets.

@felipelavinz
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipelavinz/9381598 to your computer and use it in GitHub Desktop.
Save felipelavinz/9381598 to your computer and use it in GitHub Desktop.
Ejemplo de utilización de la acción wp_ajax para hacer peticiones por AJAX a WordPress
<?php
// para peticiones de usuarios que no están logueados
add_action('wp_ajax_nopriv_get_next_posts', 'ajax_get_next_posts');
// probablemente también vas a querer que los usuarios logueados puedan hacer lo mismo
add_action('wp_ajax_get_next_posts', 'ajax_get_next_posts');
function ajax_get_next_posts(){
// usamos absint() para sanitizar el valor y recibir un int
$offset = absint( $_REQUEST['posts_offset'] );
$next_posts = new WP_Query(array(
'offset' => $offset,
'post_type' => 'post',
'post_status' => 'publish'
));
if ( $next_posts->have_posts() ) {
// devolvemos como output el listado de posts como JSON
header('Content-Type: application/json');
echo json_encode( $next_posts->posts );
// como es una petición AJAX, cortamos inmediatamente la ejecución de PHP
exit;
}
echo json_encode( array() );
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment