I use widget plugin Getting the random post & URL via ajax. I want to add function, that allows users on frontend choose category, and than display random posts from this category.
function get_random_post_tu() {
// Simple as that, get a random post
$posts = get_posts('orderby=rand&numberposts=1');
/**
* This actually gives us an array of post objects, so we should double check
* if there is indeed a post in there.
*/
if (is_array($posts) && isset($posts[0])) {
$data = array();
$data['link'] = get_permalink($posts[0]->ID);
$data['title'] = get_the_title($posts[0]->ID);
$data['thumb'] = get_the_post_thumbnail($posts[0]->ID);
$data['content'] = get_post_field('post_content', $posts[0]->ID);
/**
* Making a structure like this will make your work in the javascript
* a lot easier when you want to get the title and link from the respons
* data.
* The JSON format is always good for passing structured data (like objects
* or arrays) to a javascript function.
*/
print_r(json_encode($data));
} else {
// If there is nothing in there, print a 0
print 0;
}
die(); // this is required to return a proper result
}
It is a function php, that displays post.
jQuery(document).ready(function($) {
$('.grp_getnew').on('click', function(){
var data = {
action: 'get_random_post_tu'
};
$.post(ajax_object.ajax_url, data, function(response) {
if (response!=0) {
var $link = $("<a href='" + response.link + "'>" + response.title + "</a><span >" + response.content +"</span>");
$('.grp_content').html($link);
}
}, "json");
});
});
it's function js.
As i understand, i must call category list via wp_get_post_categories
and than i don't know, how to link category to randomizer. I need help! Help me please!