How to use forech in Wordpress using the WP_Query variable

1

Good morning! I am not able to implement a forech in a database search using the native wordpress variables, searching I found something similar but it is not what I need.

<?php global $post; 
$args = array('category' => 17); 
$custom_posts = get_posts($args);
foreach($custom_posts as $post) : setup_postdata($post);
...
endforeach;
?>

I want to return the data in a list to change the class from the first search to the second, example below:

<?php global $post; 
    $args = array('category' => 17); 
    $custom_posts = get_posts($args);
    foreach($custom_posts as $post) : setup_postdata($post);
    <div class="divA">
    </div>
    <div class="divB">
    </div>
    endforeach;
    ?>

Returning:

<div class="divA">
Teste 1
</div>
<div class="divB">
Teste 2
</div>
<div class="divA">
Teste 3
</div>
<div class="divB">
Teste 4
</div>

Would it be possible?

    
asked by anonymous 21.02.2018 / 14:12

2 answers

0

You can transform the class into a variable and create a counter, each loop checking whether the counter is even or odd and changing the class, see example:

<?php 
    global $post; 
    $args = array('category' => 17); 
    $custom_posts = get_posts($args);
    $count = 0;
    foreach($custom_posts as $post) : setup_postdata($post);
        $post_class = ($count%2 == 0) ? 'divA' : 'divB';

        echo '<div class="' . $post_class . '">';
            ...
        echo '</div>';

        $count++;
    endforeach;
?>
    
21.02.2018 / 19:39
0

If someone needs something similar, the following is the final code of the form:

<?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    global $post; 
    $args = array('category' => 14, 'orderby' => 'rand', 'order' => 'ASC'); 
    $custom_posts = get_posts($args);
    $count = 0;
    foreach($custom_posts as $post) : setup_postdata($post);
        $post_class = ($count%2 == 0) ? 'box_sistemaEsq' : 'box_sistemaDir';
?>
             <article class="<?php echo $post_class ?>">
                <div class="box_sistemaP">
                <p class="box_sistema3">
                <a href="http://<?php echo get_field('url_do_site'); ?>" target="_blank" title="<?php the_title();?>"><?php the_post_thumbnail('foto_destacada');?></a>
                <?php echo  get_the_content(); ?>
                </p>
                <p class="box_sistema2">
                <?php the_title();?>
                </p>
                <p class="box_sistema4">
                    <a href="http://<?php echo get_field('url_do_site'); ?>" target="_blank" title="<?php the_title();?>"><?php echo get_field('url_do_site'); ?></a>
                </p>
                </div>
            </article> 
<?php
        $count++;
    endforeach;
   wp_reset_query();
?>
    
08.03.2018 / 14:53