Grow your CSS skills. Land your dream job.

Semi-Complex PHP Loop

  • # December 27, 2012 at 6:30 pm

    I’m stuck on trying to write a loop for a wordpress template. I’m wanting to use the wordpress loop to show mini snippets of blog posts. I wanted to show three items per row and every two rows, have an add show up. Could anyone help me with this?

    This is what my code looks like in HTML.

    	<div class="entry">
    <?php query_posts('cat=23'); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <div class="one-third column">
    <img src="<?php the_post_thumbnail();?>" alt="<?php post_title(); ?>" />
    <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
    </div>
    <?php endwhile; endif; // end of the loop. ?>
    <?php wp_reset_query(); ?>
    <div class="clear"></div>
    </div><!--/ .entry -->

    # December 27, 2012 at 6:59 pm

    Could you clarify? Are your “three items” referring to three snippets of blog posts, and what is an “add”?

    # December 27, 2012 at 7:09 pm

    I guess you could try something like this:

    < ?php
    $count = 0;
    global $count;
    ?>
    < ?php query_posts('cat=23'); ?>
    < ?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    < ?php $count++; ?>

    < ?php if($count == 6) {?>

    < ?php $count = 0; /* Reset the counter*/ ?>
    < ?php } else { ?>

    < ?php } ?>
    < ?php endwhile; endif; // end of the loop. ?>
    < ?php wp_reset_query(); ?>


    EDIT: Failing with “code” markdown… Can’t seeem to fix it. Check it out on codepen:

    http://codepen.io/joe/pen/Jcfbj

    # December 27, 2012 at 7:35 pm

    You could make a function like this in your functions.php file:

    http://pastebin.com/h3G44H2a

    and you would call it in your theme as:

    < ?php mytheme_get_posts( 23, 2, 3 ); ?>

    where 23 is your category id, 2 is the number of posts to offset (assuming you would call the function with 0 before and place an ad between) and 3 would be the number of posts to show. this would save you prom copy-pasting the same code.

    # December 27, 2012 at 9:29 pm

    Thanks for the help guys. I really appreciate it. I looked at the code again and I forgot a key part. Every three items, has a “row” class wrapped around them along with an “alpha” class on the first item and an “omega” class on the third item of the row.

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".