WordPress自定义模板 - 用PHP合并两个foreach循环

编程语言 2026-07-07

我在尝试创建一个自定义的WordPress模板,但我无法把我需要的代码组合在一起。

我想把这两个PHP代码合并。

我尝试输出一个包含3 篇文章的列表,标题前缀带有一个数字表情符号。

示例期望输出:

1️⃣文章标题1

2️⃣文章标题2

3️⃣文章标题3

1部分代码:

<?php
/**
 * Template Name: emojies LINKS SCRAPPER
 */

    global $post;
      $counter = 1;
    $myposts = get_posts( array(
        'orderby'        => 'rand',
        'posts_per_page' => 3,
        'offset'         => 0,
        'category'       => 187
    ) );

    if ( $myposts ) {
        foreach ( $myposts as $post ) : 
        setup_postdata( $post ); ?>

// ...do something...

<?php the_title(); ?>

        <?php
        endforeach;
        wp_reset_postdata();
    }
    ?>

2部分代码:

<?php $numbers = array("1️⃣", "2️⃣", "3️⃣"); 
foreach ($numbers as $value) {
  echo "$value <br>";
}
?>

解决方案

我不会再使用第二个foreach循环。假设WordPress没有为 get_posts 返回的数据指定键,你可以使用默认键来匹配数字数组中的键。你的代码可能看起来像下面这样:

$numbers = array("1️⃣", "2️⃣", "3️⃣");
if ( $myposts ) {
    foreach ( $myposts as $key => $post ) :
        setup_postdata( $post ); ?>

        // ...do something...

        <?php echo $numbers[$key]; the_title(); ?>

    <?php
    endforeach;
    wp_reset_postdata();
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章