Im new to wordpress
I have four variables and four posts
I want assign each icon as thumbnail to each post by order,
is there any ways to assign them without duplicate the function?
here is my code:
<?php
$icons = array(
'icon_1' => '<picture><i ></i></picture>',
'icon_2' => '<picture><i ></i></picture>',
'icon_3' => '<picture><i ></i></picture>',
'icon_4' => '<picture><i ></i></picture>',
);
$args = array(
'post_type' => 'content',
'post_status' => 'publish',
'category_name' => 'service',
'posts_per_page' => 4,
'order' => 'ASC',
);
$arr_posts = new WP_Query( $args );
if ( $arr_posts->have_posts() ) :
while ( $arr_posts->have_posts() ) :
$arr_posts->the_post();
?>
<li>
<?php
if ( has_post_thumbnail() ) :
?>
<picture>
<?php the_post_thumbnail(); ?>
</picture>
<?php
else :
if ( has_post_thumbnail() == false) {
foreach ($icons as $key => $value) {
return $value;
}
}
endif
?>
<span></span>
<h4><?php the_title(); ?></h4>
<?php the_content(); ?>
</li>
<?php
endwhile;
endif;
?>
CodePudding user response:
Yes, I just refactor your code :
$icons = [
'icon_1' => '<picture><i ></i></picture>',
'icon_2' => '<picture><i ></i></picture>',
'icon_3' => '<picture><i ></i>
</picture>',
'icon_4' => '<picture><i ></i></picture>',
];
$query = new WP_Query( [
'post_type' => 'content',
'post_status' => 'publish',
'category_name' => 'service',
'posts_per_page' => 4,
'order' => 'ASC',
] );
if ($query->have_posts()) {
$counter = 1;
while ($query->have_posts()) {
$query->the_post();
echo sprintf('<li>%s <h4>%s</h4> %s</li>',
has_post_thumbnail() ? get_the_post_thumbnail() :
$icons['icon_' . $counter],
get_the_title(),
get_the_content()
);
$counter ;
}