Pre_Get_Posts如何在WP管理中按角色进行筛选

时间:2016-08-15 作者:Putra Fajar Hasanuddin

如何在wordpress admin中按角色筛选

im已添加“按角色筛选”下拉列表enter image description here

使用此代码http://pastebin.com/Zbv3UhVH

但我坚持下去了pre_get_posts

function add_role_filter_to_posts_query( $query ) {

    global $post_type, $pagenow;

    if ($pagenow == \'edit.php\' && $post_type == \'post\') {

        if ( isset( $_GET[\'user_role\'] ) ) {

            $role = $_GET[\'user_role\'] ); // return string \'contributor_facebook\'

            // TO DO 

        }

    }

}
add_action( \'pre_get_posts\', \'add_role_filter_to_posts_query\' );
我必须做的是过滤它。。

谢谢

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

我要问两个问题。这看起来像这样:

function add_role_filter_to_posts_administration(){

    //execute only on the \'post\' content type
    global $post_type;
    if($post_type == \'post\'){

        $user_role  = \'\';
        // Get all user roles
        $user_roles = array();
        foreach ( get_editable_roles() as $key => $values ) :
            $user_roles[ $key ] = $values[\'name\'];
        endforeach;
        // Set a selected user role
        if ( ! empty( $_GET[\'user_role\'] ) ) {
            $user_role  = sanitize_text_field( $_GET[\'user_role\'] );
        }

        ?><select name=\'user_role\'>
        <option value=\'\'><?php _e( \'All Roles\', \'papasemarone\' ); ?></option><?php
        foreach ( $user_roles as $key => $value ) :
            ?><option <?php selected( $user_role, $key ); ?> value=\'<?php echo $key; ?>\'><?php echo $value; ?></option><?php
        endforeach;
        ?></select><?php

    }

}
add_action(\'restrict_manage_posts\',\'add_role_filter_to_posts_administration\');

function add_role_filter_to_posts_query( $query ) {

    /**
     * No use on front
     * pre get posts runs everywhere
     * even if you test $pagenow after, bail as soon as possible
     */
    if ( ! is_admin() ) {
        return;
    }

    global $pagenow;

    /**
     * use $query parameter instead of global $post_type
     */
    if ( \'edit.php\' === $pagenow && \'post\' === $query->query[\'post_type\'] ) {

        if ( isset( $_GET[\'user_role\'] ) ) {
            $role = $_GET[\'user_role\']; // return string \'contributor_facebook\'
            $users   = new WP_User_Query( array( \'role\' => $role ) );
            $results = $users->get_results();

            $user_ids = array();
            foreach( $results as $result ) {
                $user_ids[] = (int) $result->ID;
            }

            /**
             * I use PHP_INT_MAX here cause 0 would not work
             * this means "user that does not exist"
             * this trick will make WP_Query return 0 posts
             */
            $user_ids = ! empty( $user_ids ) ? $user_ids : PHP_INT_MAX;

            $query->set( \'author__in\', $user_ids );

        }

    }

}
add_action( \'pre_get_posts\', \'add_role_filter_to_posts_query\' );
您需要进行用户查询以获取具有特定角色的所有用户,然后使用“author”参数查询帖子。

相关推荐