Wordpress Roles

时间:2018-04-02 作者:Kevin

我的情况是我需要array “小于或等于”指定角色的所有当前用户角色,以显示某些“分配的”内容。

我创建了一个CPT,具有一个名为gyo_kb_roleview, 所以我需要能够根据meta_query 内容所在的位置allowed 角色等于或高于当前用户角色。

所以,如果我有一个“贡献者”角色,那么只有与贡献者相等或更高级别的用户才能查看所述内容,而低于该角色的任何人都无法查看该内容。

我该怎么做?

Display Template:

<?php
// We don\'t want to allow direct access to this
defined(\'ABSPATH\') OR die(\'No direct script access allowed\');

// Get the theme header
get_header();

// Get the user\'s role
$_user = wp_get_current_user( );
$_role = \'Anonymous\';
if( is_user_logged_in() ){
    $_role = ucfirst( $_user->roles[0] );
}

// Query for our CPT taxonomies, Filter the query based on what articles should show for the allowed roles
$args = array( \'post_type\'=>\'gyo_kbs\', \'posts_per_page\'=>-1, \'orderby\' => \'menu_order\', \'order\' => \'ASC\', \'meta_query\' => array(
        array(
          \'key\' => \'gyo_kb_roleview\',
          \'value\' => $_role, // i am thinking I need to pass an array of "allowed" roles here and add an \'IN\'... i just dont know how to procure said array
        )
      ), );

$the_query = new WP_Query ( $args );
while ( $the_query -> have_posts() ) : $the_query -> the_post();

    echo \'<h1>\' . $post -> post_title . \'</h1>\';

endwhile;
wp_reset_query();

?>

<?php

// Get the theme footer
get_footer();

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

创建函数为角色指定数值:

function get_user_level($role){

    switch ($role) {

        case \'Contributor\':
            return 1;
            );
            break;
        case \'Author\':
            return 2;
            );
            break;
        case \'Editor\':
            return 4;
            break;
        case \'Administrator\':
            return 5;
            break;
        case \'Super Admin\':
            return 6;
            break;

        default:
            return 0; // default subscriber or other roles
            break;
    }

}
现在您可以不使用元查询:

$args = array( \'post_type\'=>\'gyo_kbs\', \'posts_per_page\'=>-1, \'orderby\' => \'menu_order\', \'order\' => \'ASC\'); // Removed meta query

$the_query = new WP_Query ( $args );
while ( $the_query -> have_posts() ) : $the_query -> the_post();

    $allowed_role = get_post_meta( get_the_ID(), \'gyo_kb_roleview\', true ); //get the meta value of allowed role

    if( get_user_level($_role) < get_user_level($allowed_role) ){ // $_role from your question
        continue; // skip post if the user role is less than allowed role
    }

    echo \'<h1>\' . $post -> post_title . \'</h1>\';

endwhile;
wp_reset_postdata();
更新:如果可以在post meta中保存用户角色的数值,则可以执行以下操作:

    $args = array( \'post_type\'=>\'gyo_kbs\', \'posts_per_page\'=>-1, \'orderby\' => \'menu_order\', \'order\' => \'ASC\', 
    \'meta_query\' => array(
     array(
            \'key\'     => \'gyo_kb_roleview\',
            \'value\'   => get_user_level($_role),
            \'compare\' => \'>=\'
        ),
    )
);

结束

相关推荐