doushi2902 2014-04-19 19:12
浏览 47

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

I am using the following code to list all the posts in my wordpress website and I am trying to call "selected" if the ID is the current cone selected but strangely it's calling the if statement 3 times rather than once even though all the ID's are different.

My Code:

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 "
"; ?>
    <?php endwhile;
    // Reset Query
    wp_reset_query();
    }

My Output:

<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>

I did select the third option and so it is showing that one correctly but carries on to the 4th and 5th. I'm sure its something simple but I can't see it

  • 写回答

1条回答 默认 最新

  • douluohan3403 2014-04-19 19:16
    关注

    After your variable $selected gets the value "selected", it doesn't change value in futher iterations. You should use something like

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

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?