views:

35

answers:

1

I have the following code: http://pastebin.com/ng99augD

It basically spits out five posts for the five authors I have specified in the query posts in each chunk of code and then rewinds the posts prior to the next query. This is far from ideal and would like to make the code more efficient without having to repeat all the template code for the posts over and over. I also want them to be in a random order instead of coming out in the order they have been written as I don't want any particular author to be at the top. Thanks.

A: 

I'm not sure why the use of rewind_posts() is necessary. You are creating a new query using by your use of query_posts() each time. rewind_posts() rewinds the query for re-use.

If your performance isn't suffering, it may be okay to run 5 queries to get your five authors. To avoid rewriting the same template code each time you have at least two options. Create a php file with the template code in it, and include it each time you need it:

<?php include('author_posts.php');?>

Or, better yet, create a function in your functions.php or in a plugin file that accepts your query results and outputs the template.

<?php $posts = query_posts('posts_per_page=1&author=author1');
    if(function_exists('my_authors')){my_authors($posts);}
?>

Then in your functions.php or plugin:

function my_authors($posts){
    //template code here, using $posts->ID, $posts->post_content, etc
}

The third option, which cleans up your code and the number of queries would be to use a category to display posts assigned to it here. You are making 5 queries to display five posts. To use one query to display five posts and sort randomly like you want to, edit each of the five posts and assign them to a new category, lets say:'author sampler'. Then in your template file:

<?php $posts = get_posts('category=author sampler'&order_by=rand&order=asc');
    foreach($posts as $post):?>
      <?php setup_postdata($post);
           //your posted template code follows:
       ?>
      <article id="post-<?php the_ID(); ?>">
          <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a><?php edit_post_link('Edit', ' (', ')'); ?></h2>
          <p class="p-cat">In: <?php the_category('|') ?></p>
          <p class="p-author">
              <span class="name">
                  <?php the_author_posts_link(); ?></span> <span class="avatar"><?php echo get_avatar( $email, $size = '32' ); ?>
               </span>
          </p>

          <?php //etc ?>

      <?php endforeach;?>
kevtrout
I don't want to use categories for the authors. I've gone for using a function for the code and then just calling that for each query_posts call. The problem is getting them to display randomly (using order_by=rand will only work for the actual query itself and not the order of all the queries on the page)
Cameron