There are ways to write the code more efficiently, though not necessarily WordPress-specific.
-
Only pass necessary args to your
get_posts()
callsThe only critical args you need are
posts_per_page
andcategory
; you can omit the rest -
Make an array of category IDs, and loop through the array
Loop through an array of category IDs, so you only have to use the actual loop output once
For example:
<?php
// Add category IDs here
$category_ids = array( 5, 7 );
// Loop through category IDs
foreach ( $category_ids as $cat_id ) {
// Category query args
$cat_query_args = array( 'posts_per_page' => 1, 'category' => $cat_id );
// Query posts
$cat_query = get_posts( $cat_query_args );
// Loop through cat query
foreach ($cat_query as $post ) {
setup_postdata( $post );
?>
<ul class="recent-posts-2">
<div class="cat"><a href="https://wordpress.stackexchange.com/questions/121469/<?php echo get_page_link(149); ?>">my 1. category</a></div>
<li><h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2></li>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(array( 120,120 ), array( 'class' => 'recent-thumbs' )); ?></a>
</ul>
}
}
?>
You may need to add in some other things, such as a counter for class="recent-posts-1"
, etc.