Skip to content

Instantly share code, notes, and snippets.

@claudiosanches
Last active March 8, 2017 16:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save claudiosanches/7320388 to your computer and use it in GitHub Desktop.
Save claudiosanches/7320388 to your computer and use it in GitHub Desktop.
WordPress - Last posts with ajax.
<?php
function cs_last_posts_json() {
$json = array();
$last_posts = get_posts( array(
'posts_per_page' => 5,
'post_type' => 'post'
) );
foreach ( $last_posts as $post ) {
$id = $post->ID;
$json[] = array(
'title' => get_the_title( $id ),
'link' => get_permalink( $id ),
'excerpt' => wp_trim_words( strip_shortcodes( $post->post_content ), 30 ),
'image' => wp_get_attachment_thumb_url( get_post_thumbnail_id( $id ) )
);
}
if ( isset( $_REQUEST['callback'] ) ) {
header( "Content-Type: application/javascript" );
echo sanitize_text_field( $_REQUEST['callback'] ) . '(' . json_encode( $json ) . ')';
}
die();
}
add_action( 'wp_ajax_last_posts_json', 'cs_last_posts_json' );
add_action( 'wp_ajax_nopriv_last_posts_json', 'cs_last_posts_json' );
<!DOCTYPE html>
<html>
<head>
<title>Feed</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<script>
jQuery(document).ready(function($) {
$.ajax({
type: 'GET',
url: 'http://your-site.com/wp-admin/admin-ajax.php',
dataType: 'jsonp',
crossDomain: true,
contentType: "application/json",
data: {
action: 'last_posts_json'
},
success: function(items) {
console.log(items);
html = '';
$.each(items, function(i, item) {
if (item.image) {
image = '<img src="' + item.image + '" alt="" />';
} else {
image = ''
}
html += '<li><a href="' + item.link + '">' + item.title + '</a><br />' + image + item.excerpt + '</li>';
});
$('body').append('<ul>' + html + '</ul>');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment