0

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_categoriesand than i don't know, how to link category to randomizer. I need help! Help me please!

1
  • @Fischi and if it is custom post type? Commented Feb 15, 2016 at 13:09

1 Answer 1

1

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 :)

7
  • Ohohohohohohooh! Thanks! So nice! all i have modified is in js instead ajax_url i return ajax_object.ajax_url. Thats all! 100+ to your karma! Commented Feb 15, 2016 at 12:10
  • fischi, And if it's custom post type? Commented Feb 15, 2016 at 12:18
  • And if it's custom post type? Commented Feb 15, 2016 at 13:05
  • If it is a custom post type, you just need to add 'post_type' =>'yourcustomposttype' to your arguments list :)
    – fischi
    Commented Feb 15, 2016 at 13:58
  • and wp_dropdown_categories( $args ) ? Commented Feb 15, 2016 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.