I am pulling my hair out here, I simply cannot get this to work.
I need to do a foreach loop to get all authors in a website, I then need to filter the ones with 0 published articles out and then echo the authors with articles into a UL LI with a special
My code at the moment has two functions, one to prefilter all authors that have at least one article and then in the second function count the number of authors left in the filtered array to then give the last entry in the array a special li tag. Code so far:
/*********************
Echo Filtered List
*********************/
function filtered_list() {
$authors = get_users('orderby=nicename');
$all_authors = array();
if ( count_user_posts( $author->id ) >= 1 ) {
return true;
}
}
function contributors() {
$i = 0;
filtered_list();
$len = count($all_authors);
foreach ($all_authors as $author ) {
if ( count_user_posts( $author->id ) >= 1 ) {
if ($i == $len - 1) {
echo "<li class='author-last clearfix'>";}
else {
echo "<li class='author clearfix'>";}
$i++;
If you read through your code you would probably see why it doesn’t work.
First: Scopes
Read about variable scopes in the PHP manual. Basically, a variable declared inside a function is only available inside that function, so
$all_authorsis null inside contributors() as it has never been initialized.The
filtered_listfunction should return a filtered list of authors, so you should loop, though$authorsand add the author to$all_authorsif, and only if she has 1 or more posts. After the loop, return the array.Now you can get the filtered list by setting the return value of the fist function to the $all_authors in
contributors(or better yet, just call them$authors).Now you are ready to iterate over the list of authors and find their post. To do this, you need two loops. One for authors, and one for the posts.
Hope this helps, and that you’ll learn something from it. Point is: Read though your code line by line and explain to yourself what it does.