Customizing post presentation in wordpress looping

0

I want to customize the looping of my posts to display the posts as follows, the first to the left and the second to the right, and so on. It went wrong (and I knew I would), but I ran a test like this:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
            <p align="left"><?php the_title( '<h3>', '</h3>' ); ?>
            <?php the_time( $d ); ?> 
            <?php the_category( ' ' ); ?></p>

            <p align="right"><?php the_title( '<h3>', '</h3>' ); ?>
            <?php the_time( $d ); ?> 
            <?php the_category( ' ' ); ?></p>

        <?php endwhile; else : ?>
            <p><?php _e( 'Sem posts para exibição' ); ?></p>
        <?php endif; ?>

This was just a test to see if it worked, well, it did not work ... I would like some help from the skulls, because I did not find what I wanted in the documentation ... Thank you ...

    
asked by anonymous 09.09.2016 / 03:10

1 answer

0

To do things like "once and for once," you can use the module operator . This operator works by returning the rest of a division. In such a way, it is enough that you have a counter to control each time you pass loop , and check the rest of the division for 2, something like $resto = $contador % 2; . The rest of the division by 2 tells you whether a number is even or odd, since 0 and 1 are the only possible values for this operation. By doing this check ( if ($resto == 1) ) you can perform actions instead, instead. See this snippet in JS that best exemplifies the situation:

var count = 0;

for(var i = 0; i <= 10; i++){
  var resto = count % 2;
  if(resto == 1){
    $('.target').append("<p>" + i + " é impar </p>");
  }
  else{ //resto == 0
    $('.target').append("<p>" + i + " é par </p>");
  }
  
  ++count;
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="target"></div>

You can do the same thing in your loop . In a simplified way, you can do:

<?php

$count = 0;

if ( have_posts() ) : while ( have_posts() ) : the_post(); 

    if ($count % 2 == 1){
        $align = "left";
    } else{
        $align = "right";
    }

    ?>

    <p align="<?php echo $align?>"><?php the_title( '<h3>', '</h3>' ); ?>
        <?php the_time( $d ); ?> 
        <?php the_category( ' ' ); ?>
    </p>

    <?php ++$count; ?>

<?php endwhile; endif; ?>

So, the home passage of the loop , you'll align either the left, or the right.

But see, <p align="left"> or <p align="left"> will only justify the text to the specified direction. If you want to do something like a grid, or each post floating on a different side, my recommendation is to use things like float: left and a certain length for each container of the post. But that, of course, is a kick. It all depends on what you are trying to do!

    
09.09.2016 / 14:32