0

Im listing current category of all author list but I want to list random author list from current category.

I was try 'order' => 'RAND', RAND code its not worked.

My Code:

function getCurrentCatID(){
  global $wp_query;
  if(is_category() || is_single()){
    $cat_ID = get_query_var('cat');
  }
  return $cat_ID;
}

$current_category_ID = getCurrentCatID();
$current_cat_id = $current_category_ID;

$author_array = array();
$args = array(
  'numberposts' => -1,
  'cat' => $current_cat_id,
  'orderby' => 'author',
  'order' => 'asc',
  'posts_per_page' => '10',
);
$cat_posts = get_posts($args);

foreach ($cat_posts as $cat_post) :
  if (!in_array($cat_post->post_author,$author_array)) {
    $author_array[] = $cat_post->post_author;
  }
endforeach;

foreach ($author_array as $author) :
  $auth = get_userdata($author)->display_name;
  $auth_link = get_userdata($author)->user_login;
  $autid= get_userdata($author)->ID;
  $link = get_author_posts_url($autid);
  echo ''. get_avatar( $autid, '46' ).'';
  echo "<a class='sidebar-aut' href='$link";
  echo "'>";
  echo '<h6>'.$auth.'</h6>';
  echo "</a>";
  echo "<div class='clearfix'></div>";
  echo "<br />";
endforeach;
2
  • You are trying to list all the authors from a particular category. Is that correct?
    – s_ha_dum
    Jan 25, 2013 at 0:29
  • Yes that correct
    – Genxer
    Jan 25, 2013 at 11:21

1 Answer 1

1

The Codex lists rand as the orderby string, not RAND. I suspect that either works but I haven't checked. But that isn't how I'd do this. I'd lean toward something like...

$current_category_ID = getCurrentCatID();
$current_cat_id = $current_category_ID;

$author_array = array();
$args = array(
  'numberposts' => -1,
  'cat' => $current_cat_id
);
$cat_posts = get_posts($args);

foreach ($cat_posts as $cat_post) :
  if (!in_array($cat_post->post_author,$author_array)) {
    $author_array[] = $cat_post->post_author;
  }
endforeach;

shuffle($author_array); // randomize

Database ORDER BY isn't terribly efficient. ORDER BY RAND is especially inefficient. That code does the sorting in PHP on a smaller array, so it should perform better.

2
  • i have a question again. How can i list 5 or 10 author? This code listing many authors. I would like to restrict the number of authors.(e.g. just list random 5 author)
    – Genxer
    Jan 30, 2013 at 17:37
  • Use array_rand to pull out however many you want.
    – s_ha_dum
    Jan 30, 2013 at 20:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.