Last active
August 29, 2015 13:57
-
-
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
This file contains 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 | |
// 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