【发布时间】:2017-02-15 17:37:08
【问题描述】:
我正在尝试从 Wordpress 元框中动态生成的复选框中保存数据。现在它几乎可以工作 - 但正如您所见,每个复选框都有相同的名称和 ID,稍后将使用它,所以它不能那样。
这就是我创建复选框的方式:
<?php
$args = array( 'post_type' => 'teachers');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
<label for="meta-checkbox-two">
<input type="checkbox" name="meta-checkbox-two" id="meta-checkbox-two" value="yes" <?php if ( isset ( $prfx_stored_meta['meta-checkbox-two'] ) ) checked( $prfx_stored_meta['meta-checkbox-two'][0], 'yes' ); ?> />
<?php the_title() ?>
</label>
<?php endwhile; ?>
这是节省:
// Checks for input and saves
if( isset( $_POST[ 'meta-checkbox-two' ] ) ) {
update_post_meta( $post_id, 'meta-checkbox-two', 'yes' );
} else {
update_post_meta( $post_id, 'meta-checkbox-two', '' );
}
正如我所说,它几乎可以工作 - 它保存了所有称为“meta-checkbox-two”的东西 - 意思是一切,这不是目标。
这就是我迷路的地方。我正在尝试使每个名称和 ID 都以循环正在检索的帖子 ID 结尾。下面是代码的样子:
生成复选框:
<?php
$args = array( 'post_type' => 'teachers');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
<label for="meta-checkbox-two">
<input type="checkbox" name="meta-checkbox-<?php the_ID() ?>" id="meta-checkbox-<?php the_ID() ?>" value="yes" <?php if ( isset ( $prfx_stored_meta['meta-checkbox-' . the_ID()] ) ) checked( $prfx_stored_meta['meta-checkbox-'] . the_ID(), 'yes' ); ?> />
<?php the_title() ?>
</label>
<?php endwhile; ?>
保存它们:
$args = array( 'post_type' => 'teachers');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
// Checks for input and saves
if( isset( $_POST[ 'meta-checkbox-'.the_ID()] ) ) {
update_post_meta( $post_id, 'meta-checkbox-'.the_ID(), 'yes' );
} else {
update_post_meta( $post_id, 'meta-checkbox-'.the_ID(), '' );
}
endwhile;
但在第二种情况下,数据没有保存。我做错了什么?
【问题讨论】:
标签: php wordpress loops post meta-boxes