0

I'm trying to create a custom post type loop in Wordpress. So far so good. I managed to do that. However, I would like an alternating layout for each item, like this:

Item1 > IMAGE / DESCRIPTION
Item2 > DESCRIPTION / IMAGE
Item3 > IMAGE / DESCRIPTION
Item4 > DESCRIPTION / IMAGE

You get the idea. I'm fairly new to PHP, how would you change this loop?

<?php
    $loop = new WP_Query( array( 'post_type' => 'menus', 'category_name' => '', 'ignore_sticky_posts' => 1, 'paged' => $paged ) );

    while ( $loop->have_posts() ): the_post() ?>
        <?php if ( $wp_query->current_post % 2 == 0 ) : ?>
            <h2><?php echo get_the_title(); ?></h2>
            <h2><?php echo the_content(); ?></h2>
        <?php else: ?>
            <h2><?php echo the_content(); ?></h2>
            <h2><?php echo get_the_title(); ?></h2>
        <?php endif ?>
    <?php endwhile ?>
?>

Thing is, if I do it like this I run into an undefined offset error. So I'm wondering what would be the right way to achieve this. Any input is appreciated!

Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26
Pbalazs89
  • 170
  • 12

1 Answers1

1

I think this is close. You might try just using a simple counter instead, and it seems maybe your loop setup is missing a $loop variable when setting up the post object (I tend to use it, not sure if it's required), and you're calling an object that doesn't appear to exist with 'wp_query', you would need to use $loop instead or global $post. Maybe try your loop like this:

$count = 0;

while ($loop->have_posts()): $loop->the_post();
$count++;
    if ( $count % 2 === 0 ) : ?>
        <h2><?php echo get_the_title(); ?></h2>
        <h2><?php echo the_content(); ?></h2>
    <?php else: ?>
        <h2><?php echo the_content(); ?></h2>
        <h2><?php echo get_the_title(); ?></h2>
    <?php endif ;
endwhile; ?>
Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26
DubVader
  • 1,032
  • 1
  • 6
  • 8