⭐ If you would like to buy me a coffee, well thank you very much that is mega kind! : https://www.buymeacoffee.com/honeyvig Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies
Showing posts with label coding tips. Show all posts
Showing posts with label coding tips. Show all posts

Saturday, January 26, 2013

Should You Use Inline-Blocks As A Substitute For Floats?

When it comes to developing a site layout with css, floats do most of the heavy lifting. We use them for the big blocks like our main content and sidebar and we use them for the smaller blocks inside these big ones. Are floats always the answer?

They generally work well, but sometimes they can be hard to work with. This is especially true when it comes to inside blocks like a grid of images that won’t line up as expected. Inline-blocks are another option we can use. They mimic some of the behaviors of floats that we want, while not holding some of the issues we don’t.
Inline-blocks aren’t anything new and it’s quite possible you’re already using them. I haven’t until recently. The last few sites I’ve built happened to be for photographers and the sites naturally called for grids of images and I find myself reaching for inline-blocks over floats.
CSS box model

What is an inline-block?

Inline-block is one of the values we can assign to the display property of an element. It gets its name because it has some of the characteristics of inline elements and some of block elements.
  • block elements — form boxes according to the css box-model. They have width, height, padding, border, and margin and they stack vertically on top of each other.
  • inline elements — don’t form boxes. They sit horizontally next to each other.
  • inline-block elements — act like block elements on the inside where they form boxes. On the outside they act like inline elements sitting horizontally next to each other instead of stacking on top of each other.
If you think about it, that’s not too far off from how a floated elements behaves. Floats form boxes, but they also sit next to each other instead of stacking vertically. They aren’t exactly the same of course, but the inline on the outside and block on the inside characteristics are sometimes all we really want and either a float or an inline-block might be appropriate.
How text flows around a floated block and an inline-block

The Difference Between Floats and Inline-Blocks

While floats and inline-blocks share some characteristics, there are some clear differences between the two.
  • Document flow — Floats are removed from the normal document flow allowing other elements to flow around them. Inline-blocks stay in the document flow. They don’t need to be cleared so no clearfix solutions or overflow: hidden. Of course other elements can’t flow around them and you can’t force an element below an inline-block by clearing it.
  • Horizontal position — An obvious case of this is floats can’t be centered by setting text-align: center on the parent element. In fact no positioning style you place on the parent will affect a floated element. The inline part of inline-blocks lets their parent affect their position.
  • Vertical alignment — inline-blocks align on the baseline by default. Floats align at the top. You can change the default and control where inline-blocks are vertically aligned. You can’t do this with floats. This has been the main reason I’ve been using inline-blocks more, which I’ll get to in a bit.
  • Whitespace — inline-blocks pick up html whitespace. If you have several inline-block elements each on a new line in your html they’ll display with a horizontal space between them. Floated elements will sit adjacent to each other, regardless of the html whitespace between them.
  • IE6 and IE7 — inline-blocks aren’t supported or only have partial support in IE6 and IE7. If you need to support those browsers you need to find a workaround. Probably not a big issue at this point, but worth mentioning.
Showing the whitespace issue with inline-floats
All the blocks above are set to display: inline. On the left there is whitespace between them in the code. On the right the html whitespace has been removed. That’s the only difference.

Solving the Whitespace issue

It’s possible, even likely you’ll want to use inline-blocks at times, but don’t want the horizontal space between them. There are a few methods for removing it.
  • Remove the html whitespace — Get rid of the new line character between elements in some way. Not always an elegant solution, but one that works, especially if you only have a few elements.
  • Use negative margins — You can set a negative margin equal to the space.You’ll have to adjust for the font-size as the space is based on that size. I want to say it’s 0.25em, but I’m not entirely sure. If anyone knows please leave a comment.
  • Set a font-size of 0 on the parent — No matter what size the space, a font-size of 0 means the space would also be equal to 0. Naturally you’d need to reset the size for any children that need to have a font-size.
wooden blocks floating in the bathtub
Wooden blocks floating in a bathtub

When To Use Inline-Blocks and When To Use Floats?

When to use either depends on the specifics of your design and what you’re trying to accomplish. If you need text to flow around an element then a float is the obvious answer. If you need to center the element, inline-block is the better option.
Your choice will ultimately come down to the differences between floats and inline-blocks and which characteristics of each you need.
  • Use inline-blocks — when you need more control over the vertical alignment or horizontal positioning of elements.
  • Use floats — when you need other elements to flow around an element, support older versions of IE, or don’t want to deal with the horizontal whitespace issue.
Floated blocks in a grid
The blocks above have been floated left to create a grid. Block 5 gets trapped behind block 2 because block 2 has the greatest height in its row. This is a common issue when creating a grid of images.

Floats, Inline-Blocks, and Image Grids

In my case the use of inline-blocks is to help with the vertical alignment issue. I think this is the same for many people who’ve started using them. I’ve built several sites for photographers of late and naturally those sites inevitably have grids of images all over the place.
Floats work well if all the images in the grid are the same height. As soon as they aren’t, which is most of the time, floats get hung up behind whichever image in a row is tallest. This is because they are removed from the normal document flow.
Inline-blocks don’t have this issue, since they remain in the document flow. When it’s time for a new row of images they automatically clear the entire row above. In order to have the floated elements clear we’d need to specifically know which element needs to be cleared, which causes problems when things are created dynamically.
Using inline-blocks will typically make more sense here.
I’ve built a simple demo to illustrate the issue above and the different results when using floats and inline-blocks.
inline-blocks in a grid
The blocks above have been set to display as inline-blocks. Since they aren’t removed from the document flow, no block gets trapped behind another in the row above.

Inline-Blocks in Navigation

Another potential place you might choose inline-block is in horizontal navigation bars. We typically float the links and then set them as block level elements. I also find myself setting the list-items inline. If there’s a lot of switching inline and block values to work with floats, maybe a better solution is to use inline-blocks instead.
Any place you want elements in a row or over several rows you might want to consider using inline-blocks as opposed to floats. Of course, a table will also work in these circumstances. They are for aligning things in rows and columns after all.
If you’re building something more complex with rows and columns then a table (whether html or css) might be your best option, but when it’s something simple think of inline-blocks.
Vintage wooden block

Summary

We make great use of floats in our layouts, but are they always the tool we should reach for? Sometimes inline-blocks will be the better choice, especially if your goal is to lay out blocks in rows, like a grid of images or a horizontal list of links.
Inline-block elements take on the characteristics of inline elements from the outside and block level elements on the inside. This makes them very similar to floated elements, with a few key differences.
These differences are what will suggest which is more appropriate to use. If you’re having an issue with vertical alignment or horizontal position, you probably want to use an inline-block. If you need more control over a single element and how other elements react to it, you probably want a float.
And of course, a table (html or css) might end up being your best option depending on what you’re trying to accomplish.

Thursday, January 24, 2013

10 Tips for Writing Better CSS

Writing your first piece of css code can seem really weird if you’re used to working with tables, or just haven’t written code before. In this article I want to talk about 10 different ways you can write proper and clean css code as well as streamline the process and ensure you’re getting the job done as quickly and efficiently as possible.

1. Always start with a CSS Reset

Writing CSS code can become a bit mundane when you’re having to write specific code over and over again just to get various browsers to display your layout the same. That is where CSS Reset’s come into play. With industry leaders like Eric Meyer releasing a pretty kick ass css reset stylesheet, there’s really no reason to not get all of your browsers ‘back to zero’ and build off of it. Some people have said that css reset stylesheets aren’t needed (Jonathan Snook being one of them), but once you get used to the reset and what items you’re coding, it becomes much easier to ensure that every browser is displaying items properly.

2. Indent your css rules for easier scanning

When you’ve got 500 lines of css code to sift through, it can become straining on the eyes. So, instead of writing out the css code like this:
.classname {
background: #FFF;
border: 0;
color: #252525;
float: left;
margin: 0;
padding: 0;
}
You can indent the rules to make scrolling through the file and finding the proper css classes and ID’s easier.
.classname {
 background: #FFF;
 border: 0;
 color: #252525;
 float: left;
 margin: 0;
 padding: 0;
}

3. Comments are your very best friend

In the spirit of keeping your stylesheets clean and easy to read, comments are going to be a great way for you to keep things structured and clean. By commenting out blocks of code, the scanning process we mentioned above becomes another 10X easier because you can scan and look for items such as the header, sidebar, content and footer code because you have each section of code commented like below.
 /********** HEADER code here **********/
Doing this will not only save you time scanning but will be great for your clients when you pass along the code – they’ll be able to find items easier, fix items themselves and not have to email you 4-5 times a week for simple 1-2 minute changes. The benefits of clean css code goes much deeper than making the file look pretty.

4. One Rule = One Line … Multiple Rules = Multiple Lines

Following the simple rule above, you can cut down on the clutter in your css files drastically. Below you will see the two different ways you can write your css code out – some people swear by putting everything on a single line, but I tend to believe in the above mentioned rules: one rule = one line, while multiple rules = multiple lines.
.classname { border: 0; }

.classname {
 background: #FFF;
 border: 0;
 color: #252525;
 float: left;
 margin: 0;
 padding: 0;
}

5. Stay consistant with your code

I’ve not only stayed cosistant in my css styles throughout stylesheets I’ve written, but if you look at the various css code I’ve displayed in this article, you’ll see I have actually stayed consistant with them. It isn’t something you’ll tend to visually notice on a daily basis, but over time you’ll begin to pick up patterns on how you write specific lines of code and it will throw you off if you ever write something different. It makes things harder to find and runs your time up when you could have easily cured the problem by sticking to a specific style of writing for your css stylesheet files.
For instance, if you’re writing everything in blocks of code to separate different items of the page for easy editing, keep with it. Don’t change the way you write your code every time you write a new stylesheet. It’s just not practical.

6. Separate your hacks and conditional elements

Some people will swear against using any css hacks and scream something like “if the user can’t upgrade his browser, to hell with him!” – which we all know is not something everyone is in the position to say. So, writing conditional elements and various css hacks in your files becomes pretty much routine. But the idea that all of it needs to be in one file is wrong (in my opinion). Separating them from your main style.css file will allow you to make edits and adjustments to the hacks and conditional elements easier, without effecting your main css code.
A sample of how to separate your files could be like the code below, which would give you a separate stylesheet if your viewer is using any internet explorer browser less than IE8, along with your main style.css file and a print.css file (make sure you add the proper “” characters at the beginning and end of each line in the code below):
     link rel="stylesheet" type="text/css" href="/css/style.css" media="screen, projection"
     !--[if lt IE 8]
       link rel="stylesheet" type="text/css" href="/css/ie.css" media="screen"
       ![endif]--
       link rel="stylesheet" type="text/css" href="/css/print.css" media="print"

7. Learn (and use) shorthand code

Shorthand css code will allow you to speed up the writing process, cut down on clutter in your stylesheets and will allow you to find things much easier. So, why do so many people still write out their css in a long hand format like this?!?!
.classname {
 margin-left: 1px;
 margin-right: 2px;
 margin-bottom: 4px;
 margin-top: 1px;
}
Writing the above code in shorthand format allow things to look so much cleaner. Shorthand code also follow the clockwise writing format – so each number (as seen below) goes like this: top, right, bottom, left.
.classname { margin: 1px 2px 4px 1px; }

8. Create and use a table of contents

Writing in a table of contents in the beginning of your stylesheet will allow you, as well as anyone else viewing your css file, to find where the specific items in your code are before they even have to scroll. Need to find and edit your content code to change a color of a specific piece of text? Looking at the table of contents shows you that it’s the third header down in the css file. Coupled with the rule from above about adding in commented areas to separate blocks of code, this will help keep your code lean and mean – plus, very easy to edit.
/*****************************************************
1. HEADER code
2. NAVIGATION code
3. CONTENT code
4. SIDEBAR code
5. FOOTER code
*****************************************************/

9. Keep your class and ID names easy to follow

There’s nothing worse than going to edit a piece of code, only to find that they named their css code like this:
.wackyblueline5 { ... }
.leftsidesection { ... }
#bodyleftcurve2 { ... }
Picking the proper naming structure for your css classes and ID’s can help you dig through your stylesheet files as well as your html files, to edit the code. I would recommend sticking with names like this, which keep things clear and easy to understand:
.sidebar-title { ... }
.postwrap { ... }
.main-navigation { ... }

10. Alphabetize your css code for easier reading

This is one tip that I’ve just come to realize is actually worthwhile and one that I’m beginning to use on a daily basis when writing css code. Alphabetizing your rules will allow you to easily jump in, find the proper line of code you need to edit, change it and move on. Check out the code below and see how the beginning letters of each line go in alphabetical order, which allows you to easily scan and find the proper line. Looking for font-size? well, you know where F comes in the alphabet, right? So finding it in these lines of code will be much easier.
.classname {
 border: 1px solid #dedede;
 color: #000;
 font-size: 18px;
 line-height: 24px;
 margin: 48px;
 padding: 0;
 position: relative;
 z-index: 101;
}

What about you? Any tips for us?

I know the readers here are highly skilled so I would like to pass the baton on to you and let you weigh in, in the comments section with what your thoughts are on these tips and also share tips of your own. I’m looking forward to finding out what you think works best. I hope you enjoyed the article and would love if you spread the word through your various social media profiles. Thanks!

Saturday, June 9, 2012

Front-End Author Listing And User Search For WordPress

This article will guide you through the process of creating a front-end page in WordPress that lists your authors. We’ll discuss why you would want to do this, we’ll introduce the WP_User_Query class, and then we’ll put it it all together.

User Engagement And WordPress

At its core, WordPress is a rock-solid publishing platform. With a beautiful and easy to use interface, and support for custom post types and post formats, publishers have the flexibility to do what they do best: write content.
However, WordPress is lacking in social interaction between content authors and readers. BuddyPress is trying to solve this, but I believe it’s going in the wrong direction by trying to be a full-fledged social network.
A big phrase in the publishing world is “user engagement.” This is about getting readers to spend more time on the website, actively searching for content and even generating their own. While one could write a few books on the subject, here are a few things a WordPress publisher can do:
  • Create a daily or weekly newsletter, with top stories from selected categories;
  • Provide an editorial-driven open forum in which editors propose themes, stories and questions and readers comment on them;
  • Continue the discussion of articles on social platforms;
  • Encourage users to submit articles and images for contests;
  • Highlight your authors.

Listing Authors, And Why It’s A Good Thing

If you’re a publisher, your authors are your biggest asset. They are the content creators. Their writing gets consumed by millions of people all over the world.
Showcasing them exposes them for what they really are: authorities. Your authors will thank you for acknowledging them, and readers will get to see the human face behind the technology.

Coding The Perfect Author Listing

Here are the things we want to achieve with our page:
  • Build it as a WordPress plugin so that we can reuse it more easily;
  • Display the name, biography, number of posts and latest published post of all authors;
  • Paginate the listing if we have many authors;
  • Make the listing searchable.

Introducing WP_User_Query And get_users

The WP_User_Query class allows us to query the user database.
Besides returning an array of users, WP_User_Query returns general information about the query and, most importantly, the total number of users (for pagination).
One can use WP_User_Query by passing a series of arguments and listing the output.
01$my_authors = new WP_User_Query(
02    array(
03        'blog_id' => $GLOBALS['blog_id'],
04        'role' => '',
05        'meta_key' => '',
06        'meta_value' => '',
07        'meta_compare' => '',
08        'include' => array(),
09        'exclude' => array(),
10        'search' => '',
11        'orderby' => 'login',
12        'order' => 'ASC',
13        'offset' => '',
14        'number' => '',
15        'count_total' => true,
16        'fields' => 'all',
17        'who' => ''
18));
We’ll focus on only a few arguments, rather than go through all of them:
  • role
    This is the user’s role. In our example, we’ll query for author.
  • offset
    The first n users to be skipped in the returned array.
  • number
    Limit the total number of users returned.
We also have the get_users class, which (like WP_User_Query) returns a number of users based on the parameters set.
The important difference between the two is that get_users only returns an array of users and their meta data, whereas WP_User_Query returns extra information such as the total number of users (which is useful when it comes time to paginate).

Simple User Listing Using get_users()

Before moving on with the full user listing, including pagination and search, let’s see get_users in action.
If all you need is a simple list of authors, then you could just use wp_list_authors, like so:
1wp_list_authors('show_fullname=1&optioncount=1&orderby=post_count&order=DESC&number=3');

Creating A Plugin And Shortcode With A Bit More Functionality

A simple and straightforward way to build our user listing would be to create a shortcode that we could include on any page we like. Housing this type of functionality in a plugin is ideal, so that we don’t have to worry about migrating it when we change the theme.
Let’s keep it simple. Our entire plugin will consist of just one file: simple-user-listing.php.
001<?php
002/*
003Plugin Name: Simple User Listing
004Plugin URI: http://cozmoslabs.com
005Description: Create a simple shortcode to list our WordPress users.
006Author: Cristian Antohe
007Version: 0.1
008Author URI: http://cozmoslabs.com
009*/
010 
011function sul_user_listing($atts, $content = null) {
012    global $post;
013 
014    extract(shortcode_atts(array(
015        "role" => '',
016        "number" => '10'
017    ), $atts));
018 
019    $role = sanitize_text_field($role);
020    $number = sanitize_text_field($number);
021 
022    // We're outputting a lot of HTML, and the easiest way
023    // to do it is with output buffering from PHP.
024    ob_start();
025 
026    // Get the Search Term
027    $search = ( isset($_GET["as"]) ) ? sanitize_text_field($_GET["as"]) : false ;
028 
029    // Get Query Var for pagination. This already exists in WordPress
030    $page = (get_query_var('paged')) ? get_query_var('paged') : 1;
031 
032    // Calculate the offset (i.e. how many users we should skip)
033    $offset = ($page - 1) * $number;
034 
035    if ($search){
036        // Generate the query based on search field
037        $my_users = new WP_User_Query(
038            array(
039                'role' => $role,
040                'search' => '*' . $search . '*'
041            ));
042    } else {
043        // Generate the query
044        $my_users = new WP_User_Query(
045            array(
046                'role' => 'author',
047                'offset' => $offset ,
048                'number' => $number
049            ));
050    }
051 
052    // Get the total number of authors. Based on this, offset and number
053    // per page, we'll generate our pagination.
054    $total_authors = $my_users->total_users;
055 
056    // Calculate the total number of pages for the pagination
057    $total_pages = intval($total_authors / $number) + 1;
058 
059    // The authors object.
060    $authors = $my_users->get_results();
061?>
062 
063    <div class="author-search">
064    <h2>Search authors by name</h2>
065        <form method="get" id="sul-searchform" action="<?php the_permalink() ?>">
066            <label for="as" class="assistive-text">Search</label>
067            <input type="text" class="field" name="as" id="sul-s" placeholder="Search Authors" />
068            <input type="submit" class="submit" name="submit" id="sul-searchsubmit" value="Search Authors" />
069        </form>
070    <?php
071    if($search){ ?>
072        <h2 >Search Results for: <em><?php echo $search; ?></em></h2>
073        <a href="<?php the_permalink(); ?>">Back To Author Listing</a>
074    <?php } ?>
075 
076    </div><!-- .author-search -->
077 
078<?php if (!empty($authors))   { ?>
079    <ul class="author-list">
080<?php
081    // loop through each author
082    foreach($authors as $author){
083        $author_info = get_userdata($author->ID);
084        ?>
085        <li>
086            <?php echo get_avatar( $author->ID, 90 ); ?>
087            <h2><a href="<?php echo get_author_posts_url($author->ID); ?>"><?php echo $author_info->display_name; ?></a> - <?php echo count_user_posts( $author->ID ); ?> posts</h2>
088            <p><?php echo $author_info->description; ?></p>
089            <?php $latest_post = new WP_Query( "author=$author->ID&post_count=1" );
090            if (!empty($latest_post->post)){ ?>
091            <p><strong>Latest Article:</strong>
092            <a href="<?php echo get_permalink($latest_post->post->ID) ?>">
093                <?php echo get_the_title($latest_post->post->ID) ;?>
094            </a></p>
095            <?php } //endif ?>
096            <p><a href="<?php echo get_author_posts_url($author->ID); ?> ">Read <?php echo $author_info->display_name; ?> posts</a></p>
097        </li>
098        <?php
099    }
100?>
101    </ul> <!-- .author-list -->
102<?php } else { ?>
103    <h2>No authors found</h2>
104<? } //endif ?>
105 
106    <nav id="nav-single" style="clear:both; float:none; margin-top:20px;">
107        <h3 class="assistive-text">Post navigation</h3>
108        <?php if ($page != 1) { ?>
109            <span class="nav-previous"><a rel="prev" href="<?php the_permalink() ?>page/<?php echo $page - 1; ?>/"><span class="meta-nav">←</span> Previous</a></span>
110        <?php } ?>
111 
112        <?php if ($page < $total_pages ) { ?>
113            <span class="nav-next"><a rel="next" href="<?php the_permalink() ?>page/<?php echo $page + 1; ?>/">Next <span class="meta-nav">→</span></a></span>
114        <?php } ?>
115    </nav>
116 
117    <?php
118    // Output the content.
119    $output = ob_get_contents();
120    ob_end_clean();
121 
122    // Return only if we're inside a page. This won't list anything on a post or archive page.
123    if (is_page()) return  $output;
124 
125}
126 
127// Add the shortcode to WordPress.
128add_shortcode('userlisting', 'sul_user_listing');
129?>

Breaking Down The Code

The top of our plugin’s main PHP file must contain the standard header of information. This header tells WordPress that our plugin exists, and it adds it to the plugin management screen so that it can be activated, loaded and run.
1/*
2Plugin Name: Simple User Listing
3Plugin URI: http://cozmoslabs.com
4Description: Create a simple shortcode to list our WordPress users.
5Author: Cristian Antohe
6Version: 0.1
7Author URI: http://cozmoslabs.com
8*/

Creating a Shortcode

Adding a new shortcode in WordPress is rather easy. We find the function that returns the desired output (in our case, sul_user_listing), and then we add it using the add_shortcode WordPress function.
1function sul_user_listing($atts, $content = null) {
2// return our output
3}
4add_shortcode('userlisting', 'sul_user_listing');

Extracting Our Shortcode Arguments

We want to be able to list users based on their roles and to control how many users are displayed on the page. We do this through shortcode arguments. We’ll add the shortcode to our theme in this way: [userlisting role="author" number="15"]. This will allow us to reuse the plugin to list our subscribers as well.
To do this, we need to use shortcode arguments:
1extract(shortcode_atts(array(
2    "role" => '',
3    "number" => '10'
4), $atts));
The extract function imports variables into our function from an array. The WordPress function shortcode_atts basically returns an array with our arguments; and we’ll set up some defaults in case none are found.
Note that the role default is an empty string, which would list all users regardless of their role.

Shortcodes Should Never Echo Stuff Out

The return value of a shortcode handler function gets inserted into the post content’s output in place of the shortcode. You should use return and not echo; anything that is echoed will be outputted to the browser but will probably appear above everything else. You would also probably get “headers already sent” type of errors.
For simplicity, we’re buffering the output through ob_start(), so we put everything into an object and return it once we’re done.

Setting Up Our Variables

Now we can start building our listing of authors. First, we need to set up a few variables:
  • $search
    This takes the GET parameter as if it exists.
  • $page
    The get_query_var for the pagination. This already exists in WordPress.
  • $offset
    Calculate the offset (i.e. how many users to skip when paginating).
  • $total_authors
    Get the total number of authors.
  • $total_pages
    Calculate the total number of pages for the pagination.

The Query

We actually have two queries: the default listing and the search results.
01if ($search){
02    // Generate the query based on search field
03    $my_users = new WP_User_Query(
04        array(
05            'role' => $role,
06            'search' => '*' . $search . '*'
07        ));
08} else {
09    // Generate the query
10    $my_users = new WP_User_Query(
11        array(
12            'role' => 'author',
13            'offset' => $offset ,
14            'number' => $number
15        ));
16}

WP_User_Query->total_users and WP_User_Query->get_results

WP_User_Query provides us with two useful functions, among others:
  • total_users
    Returns the total number of authors. This, the offset and the number of users per page will generate our pagination.
  • get_results
    Returns an object with the authors alone. This is similar to what get_users() returns.

The Search Form

For the search, we’re using a simple form. There’s nothing complex here.
01<div class="author-search">
02<h2>Search authors by name</h2>
03    <form method="get" id="sul-searchform" action="<?php the_permalink() ?>">
04        <label for="as" class="assistive-text">Search</label>
05        <input type="text" class="field" name="as" id="s" placeholder="Search Authors" />
06        <input type="submit" class="submit" name="submit" id="searchsubmit" value="Search Authors" />
07    </form>
08<?php
09if($search){ ?>
10    <h2 >Search Results for: <em><?php echo $search; ?></em></h2>
11    <a href="<?php the_permalink(); ?>">Back To Author Listing</a>
12<?php } ?>
13 
14</div><!-- .author-search -->

User Data and Listing the Authors

Looping through our results is fairly simple. However, getting information about users is a bit confusing in WordPress. You see, there are a lot of ways to get user data. We could get it directly from the returned query; we could use general functions such as get_userdata, get_user_meta, the_author_meta and get_the_author_meta; or we could even use dedicated functions such as the_author_link and the_author_posts.
We’ll just use get_userdata plus two other functions: get_author_posts_url and get_avatar.
01<?php if (!empty($authors))   { ?>
02    <ul class="author-list">
03<?php
04    // loop through each author
05    foreach($authors as $author){
06        $author_info = get_userdata($author->ID);
07        ?>
08        <li>
09            <?php echo get_avatar( $author->ID, 90 ); ?>
10            <h2><a href="<?php echo get_author_posts_url($author->ID); ?>"><?php echo $author_info->display_name; ?></a> - <?php echo count_user_posts( $author->ID ); ?> posts</h2>
11            <p><?php echo $author_info->description; ?></p>
12            <?php $latest_post = new WP_Query( "author=$author->ID&post_count=1" );
13            if (!empty($latest_post->post)){ ?>
14            <p><strong>Latest Article:</strong>
15            <a href="<?php echo get_permalink($latest_post->post->ID) ?>">
16                <?php echo get_the_title($latest_post->post->ID) ;?>
17            </a></p>
18            <?php } //endif ?>
19            <p><a href="<?php echo get_author_posts_url($author->ID); ?> ">Read <?php echo $author_info->display_name; ?> posts</a></p>
20        </li>
21        <?php
22    }
23?>
24    </ul> <!-- .author-list -->
25<?php } else { ?>
26    <h2>No authors found</h2>
27<? } //endif ?>

Pagination

We need pagination because each listing will generate two extra queries. So, if we were listing 100 people, we would end up with 200 extra queries per page. That’s a bit much, so pagination is really needed. Otherwise, for websites with many authors, the load could get so heavy that it brings down the website.
01<nav id="nav-single" style="clear:both; float:none; margin-top:20px;">
02    <h3 class="assistive-text">Post navigation</h3>
03    <?php if ($page != 1) { ?>
04        <span class="nav-previous"><a rel="prev" href="<?php the_permalink() ?>page/<?php echo $page - 1; ?>/"><span class="meta-nav">←</span> Previous</a></span>
05    <?php } ?>
06 
07    <?php if ($page < $total_pages ) { ?>
08        <span class="nav-next"><a rel="next" href="<?php the_permalink() ?>page/<?php echo $page + 1; ?>/">Next <span class="meta-nav">→</span></a></span>
09    <?php } ?>
10</nav>

Final Thoughts

We’ve discussed the code for an authors listing, but it has so many more uses:
  • List your company’s employees;
  • Showcase users who have won a competition (by listing users with the role of “winners”);
  • Present your company’s departments, each with its respective team (based on user roles).
If you allow users to register on your website, you could use more or less the same code to generate any listing of users based on your needs. If you require users to log in in order to comment (an effective way to stop automated spam), then listing users and their number of comments could increase engagement.
Have you used something similar for a project? If so, let us know in the comments!