i have a question about improving my solution.
For my task i build a Gutenberg block which shows the latest 5 Posts. This Posts show also the Category Name in the Frontend part which have different styling each.
so I'm using the get_post() function to get all Posts, but there comes no Categories which is the reason i also used wp_get_post_categories() function.
This works fine , i used a foreach in a foreach to get my results. But it kinda feel Hardcoded especially the checking if Category "News" or "informative" is used is definitely hard coded.
is there a better solution how can i archive it that i can get the Posts with there bonded Post categories?
this was the best i can get for now and it works but im not happy with this solution.
my code:
...
$post = get_posts(
[
'posts_per_page' => 5,
]
);
...
ob_start();
some echos for html
...
foreach ($post AS $p)
{
$category = wp_get_post_categories($p->ID);
foreach ($category AS $cat)
{
echo '<div>';
echo '<div class="blog-image">';
echo '<img alt="" content="'.get_the_post_thumbnail($p->ID).'">';
echo '</div>';
echo '<div class="blog-data">';
echo '<div class="data-top">';
if(get_cat_name((int) $cat) === 'News')
{
echo '<div class="blog-type"><span class="news">'.get_cat_name((int) $cat).'</span></div>';
}elseif (get_cat_name((int) $cat) === 'Informative')
{
echo '<div class="blog-type"><span class="informative">'.get_cat_name((int) $cat).'</span></div>';
}
echo '<h3 class="blog-title">'.$p->post_title.'</h3>';
echo '</div>';
echo '<div class="data-bottom">';
echo '<div class="blog-info">';
echo '<p class="blog-date">'.date("d F Y", strtotime( $p->post_date)).'</p>';
echo '<div class="blog-link"><a href='.$p->guid.' >Read more</a></div> ';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
}
echo '<br/>';
}
...
more echos to close all html tags
return ob_get_clean();
here is also how it should look: