我正在尝试使用WordPress用户查询来创建按自定义元值排序的用户列表。它是一个简单的数值,从1到100,因此需要先显示1,最后显示100,等等。
这是我的尝试,惨遭失败:
<?php
$args = array(
'role' => 'Author',
'meta_key' => 'order-number',
'orderby' => 'order-number',
'order' => 'asc',
);
$wp_user_query = new WP_User_Query($args);
$authors = $wp_user_query->get_results();
if (!empty($authors))
{
echo '<div style="float:left;">';
foreach ($authors as $author)
{
$author_info = get_userdata($author->ID);
echo '<div class="post team-member"><div class="image">';
echo get_avatar( $author_info->ID, 91 );
echo '</div>';
echo '<div class="content"><div class="title"><a href="/author/' . $author_info->user_login . '">' . $author_info->user_firstname . ' ' . $author_info->user_lastname . '</a></div>';
echo '' . substr( get_the_author_meta('user_description',$author_info->ID) , 0 , 100 ) . '...';
echo '</div></div>';
}
echo '</div>';
} else {
echo 'No authors found';
}
?>
我认为问题在于wp_user_query不按顺序支持自定义字段 - 所以我需要一个可以解决此问题的解决方案。
有什么想法吗?
答案 0 :(得分:3)
正确。 orderby参数只能接受'login'(默认值),'nicename','email','url'和'registered'的可能值。
肮脏的修复将是这样的:
<?php
global $wpdb; //Ignore this line if you're not within a function
$order = $wpdb->get_results("SELECT DISTINCT user_id FROM $wpdb->usermeta WHERE meta_key='order-number' ORDER BY meta_value ASC", "ARRAY_N");
$authors = array();
foreach($order as $aid)
$authors[] = new WP_User($aid[0]);
if (!empty($authors))
{
echo '<div style="float:left;">';
foreach ($authors as $author)
{
$author_info = get_userdata($author->ID);
echo '<div class="post team-member"><div class="image">';
echo get_avatar( $author_info->ID, 91 );
echo '</div>';
echo '<div class="content"><div class="title"><a href="/author/' . $author_info->user_login . '">' . $author_info->user_firstname . ' ' . $author_info->user_lastname . '</a></div>';
echo '' . substr( get_the_author_meta('user_description',$author_info->ID) , 0 , 100 ) . '...';
echo '</div></div>';
}
echo '</div>';
} else {
echo 'No authors found';
}
这在很大程度上是未经测试的,所以我不能保证这会直接开出来,但它应该让你开始。
希望这有帮助!
答案 1 :(得分:2)
<?php
// prepare arguments this is your query.
$args = array(
'meta_key' => 'last_name',
'query_id' => 'wps_last_name',
);
// Create the WP_User_Query object
$author_query = new WP_User_Query( $args );
?>
Add following lines to functions.php file
<?php
add_action( 'pre_user_query', 'wps_pre_user_query' );
/*
* Modify the WP_User_Query appropriately
*
* Checks for the proper query to modify and changes the default user_login for $wpdb->usermeta.meta_value
*
* @param WP_User_Query Object $query User Query object before query is executed
*/
function wps_pre_user_query( &$query ) {
global $wpdb;
if ( isset( $query->query_vars['query_id'] ) && 'wps_last_name' == $query->query_vars['query_id'] )
$query->query_orderby = str_replace( 'user_login', "$wpdb->usermeta.meta_value", $query->query_orderby );
}
?>