我创建了一个插件,该插件带有一个短代码,显示具有自定义角色的所有用户;安萨特;。这很好,但我希望能够将角色设置为短代码中的参数
这就是我想要实现的目标:[hw\\u display\\u users role=“ansatt”]
下面是我创建的函数。最重要的是,我正在尝试移动\'role\' => \'ansatt\'
转换为实际的短代码,以便轻松更改角色。
我究竟如何做到这一点?
function display_user_roles(){
$args = array(
\'role\' => \'ansatt\',
\'orderby\' => \'user_nicename\',
\'order\' => \'ASC\'
);
$users = get_users( $args );
ob_start();
echo \'<div class="owl-carousel owl-theme">\';
foreach ( $users as $user ) {
echo \'<div class="item"><a href="\' . get_author_posts_url( $user->ID, $user->user_nicename ) . \'">\';
$image1 = get_field(\'profilbilde\', $user);
echo \'<div class="hw-thumb">\';
echo \'<img class="profile1" src="\';
echo $image1[\'url\'];
echo \'"/>\';
echo \'</div>\';
echo \'<div class="hw-stilling">\'. get_field(\'stilling\', $user) . \'</div>\';
echo \'<h2 class="hw-username">\'. esc_html( $user->display_name ) . \'</h2>\';
echo \'<div class="hw-epostadresse">\'. get_field(\'epostadresse\', $user) . \'</div>\';
echo \'</a></div>\';
}
echo \'</div>\';
return ob_get_clean();
}
add_shortcode( \'hw_display_users\', \'display_user_roles\' );
编辑-工作代码
function display_user_roles( $atts ){
$args = array(
\'orderby\' => \'user_nicename\',
\'order\' => \'ASC\'
);
if ( !empty( $atts[\'role\'] ) )
$args[\'role\'] = $atts[\'role\'];
$users = get_users( $args );
ob_start();
echo \'<div class="owl-carousel owl-theme">\';
foreach ( $users as $user ) {
echo \'<div class="item"><a href="\' . get_author_posts_url( $user->ID, $user->user_nicename ) . \'">\';
$image1 = get_field(\'profilbilde\', $user);
echo \'<div class="hw-thumb">\';
echo \'<img class="profile1" src="\';
echo $image1[\'url\'];
echo \'"/>\';
echo \'</div>\';
echo \'<div class="hw-stilling">\'. get_field(\'stilling\', $user) . \'</div>\';
echo \'<h2 class="hw-username">\'. esc_html( $user->display_name ) . \'</h2>\';
echo \'<div class="hw-epostadresse">\'. get_field(\'epostadresse\', $user) . \'</div>\';
echo \'</a></div>\';
}
echo \'</div>\';
return ob_get_clean();
}
add_shortcode( \'hw_display_users\', \'display_user_roles\' );
最合适的回答,由SO网友:Frank P. Walentynowicz 整理而成
首先,您必须获取shortcode参数。将函数的声明更改为:
function display_user_roles( $atts ) {
您的短代码将是
[hw_display_users]
或
[hw_display_users role="roletopass"]
. 第一个(无参数)将使用$args数组中指定的角色。第二个将替换$args->;已传递参数的角色。添加
if ( !empty( $atts[\'role\'] ) )
$args[\'role\'] = $atts[\'role\'];
之前
$users = get_users( $args );
其余代码应正常。
有关如何使用参数处理短代码的详细信息,请参阅this.