我正在尝试在我的查询中使用来自CPT的值来填充<select>
并且CPT有数据,它显示在选择中,但它是相同的帖子九次而不是每个帖子显示一次所以我对此感到困惑。我的查询和预告如下。
<select id="wooaddresslist" name="wooaddresslist" class="form-control form-control-sm">
<option>Please select an option</option>
<?php
$posts = array();
$args = array('post_type'=>'addressbook');
$query = New WP_query($args);
if($query->have_posts()):while($query->have_posts()):$query->the_post();
$temp = array();
$temp['id'] = get_the_id();
$temp['fname'] = get_field('fname');
$temp['lname'] = get_field('lname');
$temp['company'] = get_field('company');
$temp['addr1'] = get_field('address_line_1');
$temp['addr2'] = get_field('address_line_2');
$temp['city'] = get_field('city');
$temp['state'] = get_field('state');
$temp['zip'] = get_field('zip');
$posts = $temp;
$id = $posts['id'];
$fname = $posts['fname'];
$lname = $posts['lname'];
$company = $posts['company'];
$addr1 = $posts['addr1'];
$addr2 = $posts['addr2'];
$city = $posts['city'];
$state = $posts['state'];
$zip = $posts['zip'];
if(!empty($posts)){
foreach($posts as $post){?>
<option value="<?php echo $id;?>"><?php echo $fname;?></option>
<?php }
}
endwhile;endif;wp_reset_postdata();
?>
</select>
我最终得到的是
<select id="wooaddresslist" name="wooaddresslist" class="form-control form-control-sm">
<option>Please select an option</option>
<option value="136">John</option>
<option value="136">John</option>
<option value="136">John</option>
<option value="136">John</option>
<option value="136">John</option>
<option value="136">John</option>
<option value="136">John</option>
<option value="136">John</option>
<option value="136">John</option>
</select>`
答案 0 :(得分:0)
以下是您的代码的简化版本,可以让您走上正确的轨道。乍一看,我认为发生了一些事情:我怀疑你的临时数组刚刚在循环结束时被覆盖,所以最后你只是获得了循环中最后一个条目的一堆副本。另外,为了避免混淆,我将您的自定义WP_query
重命名为$ address_book_query。
<select id="wooaddresslist" name="wooaddresslist" class="form-control form-control-sm">
<option>Please select an option</option>
<?php
$args = ['post_type'=>'post'];
$address_book_query = New WP_query($args);
if($address_book_query->have_posts()) : while($address_book_query->have_posts()) : $address_book_query->the_post();
$address_book_entry = [];
$address_book_entry['id'] = get_the_id();
$address_book_entry['fname'] = get_field('fname');
$address_book_entry['lname'] = get_field('lname');
$address_book_entry['company'] = get_field('company');
$address_book_entry['addr1'] = get_field('address_line_1');
$address_book_entry['addr2'] = get_field('address_line_2');
$address_book_entry['city'] = get_field('city');
$address_book_entry['state'] = get_field('state');
$address_book_entry['zip'] = get_field('zip');
?>
<option value="<?php echo $address_book_entry['id'];?>"><?php echo $address_book_entry['fname'];?></option>
<?php
endwhile;
endif;
wp_reset_query();
?>
</select>