如何在前端选择获取帖子类别列表?

时间:2016-02-15 作者:Александр

我使用widget插件获取随机帖子(&;通过ajax的URL。我想添加一个功能,允许前端用户选择类别,然后显示该类别中的随机帖子。

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

}
这是一个php函数,用于显示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");
    });
});
这是函数js。据我所知,我必须通过wp_get_post_categories我不知道如何将分类和随机化器联系起来。我需要帮助!请帮帮我!

1 个回复
最合适的回答,由SO网友:fischi 整理而成

首先,可以扩展AJAX功能。我想您已经正确注册了。

您可以使用WordPress函数,而不是自己对数组进行编码wp_send_json(), 其中还包括die().

我建议为“无帖子”或其他错误设置一个状态变量。

查询已在中更改$args, 如果设置了类别ID。

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

}
在前端,您需要传递下拉列表的值(在这种情况下#usecategory) 到AJAX请求。我已经内置了之前在函数中创建的错误处理。

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");
    });
});
因此,您现在需要做的就是创建一个类别下拉列表和一个按钮来触发请求。

在模板中:

// 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>
这应该是您所需要的全部:)