I need to be able to display the latest post from 4 different custom post types and then use those posts inside a carousel. Everything is working fine but I'm not happy with how my code looks as I'm repeating everything.
First I made 4 different Queries for the different custom post types:
<!--recipes -->
<?php
$recipesQuery = new WP_Query( array(
'post_type' => 'recipes',
'posts_per_page' => 1
) );
?>
<!--value -->
<?php
$valueQuery = new WP_Query( array(
'post_type' => 'value_chain',
'posts_per_page' => 1
) );
?>
<!--press-->
<?php
$pressQuery = new WP_Query( array(
'post_type' => 'press',
'posts_per_page' => 1
) );
?>
<!--multimedia -->
<?php
$mediaQuery = new WP_Query( array(
'post_type' => 'multimedia',
'posts_per_page' => 1
) );
?>
And then I repeat this code block 4 times, one for each post type:
<?php if ( $valueQuery->have_posts() ) :
while ( $valueQuery->have_posts() ) : $valueQuery->the_post(); ?>
<div class="item">
<div class="row">
<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<?php if( $thumb ):?>
<div class="col-md-6 col-sm-6 col-xs-12 back">
<div class="back"
<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
style="background-image: url('<?php echo $thumb['0'];?>');">
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="info">
<h3>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php the_title(); ?>
</a>
</h3>
<hr>
<div class="excerpt"><p></p></div>
<div class="row">
<div class="col-xs-12">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="read-more">
<?php echo _e('Leer más', 'myCustomTemplate'); ?>
</a>
</div>
</div>
</div>
</div>
<?php else: ?>
<div class="col-md-12 col-sm-12 col-xs-12 no-bg">
<div class="info">
<h3>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php the_title(); ?>
</a>
</h3>
<hr>
<div class="excerpt"><p><?php echo wp_trim_words( get_the_content(), 100 ); ?></p></div>
<div class="row">
<div class="col-xs-12">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="read-more">
<?php echo _e('Leer más', 'myCustomTemplate'); ?>
</a>
</div>
</div>
</div>
</div>
<?php endif; ?>
</div>
</div>
<?php endwhile;
endif; wp_reset_postdata(); ?>
Is there a better way to do this? I am aware I can create an array with the Custom post types but not sure how I could use it to create the carousel items.