2013-11-15 43 views
1

我在Wordpress中创建了一个自定义后端,其中的一部分就是能够从自动更新的foreach循环的案例研究列表中进行选择,并在页面上插入选定案例研究的链接。在后端的电台列表是使用下面的代码如何在foreach循环中设置一个单选按钮?

 <?php 
      $checked = ' checked="checked"'; 
      $mypostype = get_posts(array(
       'post_type' => 'case_study', 
       'showposts' => -1)); 
     ?> 

     <?php $metabox->the_field('case-study-link'); ?> 

     <p id="case-study-select">  

      <label>Which case study goes here?</label> 

       <?php foreach ($mypostype as $mypost ) { ?> 

        <input type="radio" name="<?php $metabox->the_name(); ?>" value="<?php echo get_permalink_by_name( $mypost->post_name ); ?>" <?php echo $checked; ?>> 
        <?php echo $mypost->post_title; ?> 
       <?php } ?> 
     </p> 

与使用foreach循环中的问题显然是为所选的每个单选按钮被看到,所以最后一个列表中始终是一个标记创建。我如何修改这个以确保真正选中的按钮被标记为这样?

注意:功能按预期工作 - 当您选择案例研究时,将正确的链接插入到页面中,但在后端将错误的项目显示为已选中。

+1

您需要使用条件语句设置checked属性 –

+0

什么是你想要的情况下的值将被改变复选框被检查? – karthikr

回答

1
$i = 0;//set counter 
foreach($foo as $bar) { 
    if($i == 0) { $checked = "checked";}else {$checked = '';} 
    //radio button stuff here...+ stuff with $bar... 
    echo "<input type='radio' name='my_radio' value='{$bar}' {$checked}>"; 
    $i++; 

} 

默认情况下,第一个选项被选中,但根据选定的单选按钮值

相关问题