while函数和if语句在WordPress中返回错误


while function and if statement returning incorrectly in WordPress

我使用以下代码列出我的wordpress网站中的所有帖子,如果ID是当前选择的圆锥体,我会尝试调用"selected",但奇怪的是,它调用if语句3次而不是一次,尽管所有ID都不同。

我的代码:

function test($id) {
    // The Query
    query_posts( array ('posts_per_page' => -1 ) );
    // The Loop
     while ( have_posts() ) : the_post(); 
     if ($id == get_the_ID()) { $selected = " selected"; }
     ?>
    <option value="<?php echo get_the_ID(); ?>"<?php echo $selected; ?>><?php echo get_the_title() ?></option><?php echo "'n"; ?>
    <?php endwhile;
    // Reset Query
    wp_reset_query();
    }

我的输出:

<select name="w_url">
<option value="493">TEST 1</option>
<option value="390">TEST 2</option>
<option value="388" selected>Test 3</option>
<option value="386" selected>Test 4</option>
<option value="384" selected>Test 5</option>
</select>

我确实选择了第三个选项,所以它正确地显示了这个选项,但继续到第四个和第五个。我确信它很简单,但我看不到

变量$selected获得"选定"的值后,它在以后的迭代中不会更改值。你应该使用类似的东西

if ($id == get_the_ID()) { 
    $selected = " selected"; 
} else { 
    $selected = ""; 
}