First, you can extend your AJAX function. I assume you already registered it correctly.
instead of encoding your array by yourself, you can use the WordPress function wp_send_json()
, which also includes a die()
.
I would recommend making a status variable for “no posts” or other errors as well.
The query is changed in the $args
, if the category ID is set.
function get_random_post_tu() {
// Simple as that, get a random post
// I put it in an array to make it easier to read
$args = array(
'orderby' => 'rand',
'numberposts' => 1
);
// Add the Category parameter, if set
if ( isset( $_POST['usecategory'] ) && intval( $_POST['usecategory'] ) != 0 ) {
$args['category'] = $_POST['usecategory'];
}
$posts = get_posts( $args );
/**
* This actually gives us an array of post objects, so we should double check
* if there is indeed a post in there.
*/
$data = array();
if (is_array($posts) && isset($posts[0])) {
// add this to use on frontend
$data['status'] = 'success';
$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);
} else {
// add a error status
$data['status'] = 'error';
}
// use the WordPress built in function
wp_send_json( $data ); // this is required to return a proper result
}
In the frontend you need to pass the value of the dropdown (in this case #usecategory
) to the AJAX request. I already built in the error handling that we created in the function before.
jQuery(document).ready(function($) {
$('.grp_getnew').on('click', function(){
var data = {
action: 'get_random_post_tu',
usecategory: $('#categoryselect').val()
};
$.post( ajax_url, data, function(response) {
if ( response.status != 'error' ) {
var $link = $("<a href="" + response.link + "">" + response.title + "</a><span >" + response.content +"</span>");
$('.grp_content').html($link);
}
}, "json");
});
});
So, all you need to do now is create a category dropdown and a button to fire the request.
In the template:
// Use the [Codex][1] to define the correct $args for you
<?php
$args = array(
'id' => 'categoryselect'
);
wp_dropdown_categories( $args );
?>
<button class="grp_getnew">Let's go!</button>
That should be all you need 🙂