How to Combine Two Foreach Loops in WordPress for Numbered Lists
The Challenge: Merging a WordPress Post Loop with a Custom Array
When building custom WordPress templates, you might want to combine post data with an external array—like adding emoji numbers (1️⃣, 2️⃣, 3️⃣) to a list of random posts. If you try to nest two foreach loops, you will end up duplicating your posts for every single item in the second array. Instead, you need a way to pair them up sequentially.
The Solution: Index-Based Mapping
The cleanest way to solve this is by using the array index (or key) of your posts. Since get_posts() returns a standard indexed array, you can access the current loop index directly in your foreach statement and use it to pull the corresponding emoji.
<?php
/**
* Template Name: Emojis Links Scraper
*/
global $post;
$myposts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => 3,
'offset' => 0,
'category' => 187
) );
// Define your emoji array
$emojis = array("1️⃣", "2️⃣", "3️⃣");
if ( $myposts ) {
// Use $key to get the current index (0, 1, 2)
foreach ( $myposts as $key => $post ) :
setup_postdata( $post );
// Fetch the emoji matching the current post's index
$current_emoji = isset($emojis[$key]) ? $emojis[$key] : '';
// Output the emoji followed by the post title
echo '<p>' . $current_emoji . ' ' . esc_html( get_the_title() ) . '</p>';
endforeach;
wp_reset_postdata();
}
?>Alternative Approach: Using an Incremental Counter
If you prefer not to rely on array keys, or if your array indexes aren't clean sequential numbers, you can use a simple helper counter variable that increments with each loop iteration.
<?php
global $post;
$myposts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => 3,
'category' => 187
) );
$emojis = array("1️⃣", "2️⃣", "3️⃣");
$counter = 0; // Initialize counter
if ( $myposts ) {
foreach ( $myposts as $post ) :
setup_postdata( $post );
// Use null coalescing operator to avoid undefined index notices
$current_emoji = $emojis[$counter] ?? '';
echo '<p>' . $current_emoji . ' ' . esc_html( get_the_title() ) . '</p>';
$counter++; // Increment the counter for the next post
endforeach;
wp_reset_postdata();
}
?>Pro-Tip: Security and Best Practices
- Escape Your Output: Always wrap your titles in WordPress escaping functions like
esc_html()to prevent XSS vulnerabilities. - Fallback Handling: Using the null coalescing operator (
??) orisset()prevents "Undefined index" PHP notices if you happen to query more posts than you have emojis available.