您需要将表单添加到每个帖子中,每次都添加带有帖子id的隐藏输入。然后,当nonce验证时,确保读取传入的post id,并将其与update\\u post\\u meta一起使用。
例如
if ( isset( ... ) ) {
$target_post_id = ( isset($_POST[\'target_post_id\']) )? (int)$_POST[\'target_post_id\'] : 0;
if ( $target_post_id > 0 ) {
$data = stripcslashes($_POST[\'quemcomrpou\']);
update_post_meta( $target_post_id, \'quem_comprou3\', $data);
}
}
# In your posts loop where you draw each post
$posts_query = new WP_Query( $args );
if ( $posts_query->have_posts() ) {
while ( $posts_query->have_posts() ) {
$posts_query->the_post();
$current_post_id = get_the_id();
# ... anything else for this post
$quemcomprou = get_post_meta($current_post_id, \'quem_comprou3\', true);
?>
<form method="post" action="">
<?php wp_nonce_field(\'update_drw_postmeta\',\'drw_inventory\'); ?>
<label>This is label</label>
<input type=\'text\' name=\'quemcomprou\' value=\'<?php echo $quemcomprou ?>\' />
<input type="hidden" name="target_post_id" value="<?php echo $current_post_id;?>" />
<input type=\'submit\' value=\'save\' />
</form>
<?php
}
}
这必须在循环中完成才能正常工作,因为您必须:1。使用target\\u post\\u id 2的当前posts id为每个post绘制一个表单。阅读每篇文章的文章元以显示所需内容。
听起来您当前正在查看的页面上设置值,然后读取并显示每篇文章。
在页面上使用$post应该为您提供页面,而不是页面上显示的帖子(除非您处于自定义循环中)。
要使用一个表单和多个帖子,您需要以增量方式构建表单,然后在循环后绘制它:
$posts_query = new WP_Query( $args );
$post_items = array();
if ( $posts_query->have_posts() ) {
while ( $posts_query->have_posts() ) {
$posts_query->the_post();
$current_post_id = get_the_id();
# ... anything else for this post
$quemcomprou = get_post_meta($current_post_id, \'quem_comprou3\', true);
$post_items[] = array(
\'quemcomprou\' => $quemcomprou,
\'id\' => $current_post_id,
\'title\' => get_the_title()
);
?>
<?php
}
}
if ( 0 < count($post_items) ) {
foreach ( $post_items as $item ) {
$item_id = $item[\'id\'];
$bits .= <<<HTML
<hr />
<label>{$item[\'title\']}</label>
<input type="text" name="quemcomprou[{$item_id}]" value="{$item[\'quemcomprou\']}" />
HTML;
}
}
?>
<form method="post" action="">
<?php wp_nonce_field(\'update_drw_postmeta\',\'drw_inventory\'); ?>
{$bits}
<input type=\'submit\' value=\'save\' />
</form>
然后,顶部的处理必须检查并处理数组类型值:
if ( isset($_POST[\'quemcomprou\']) && is_array($_POST[\'quemcomprou\']) && 0 < count($_POST[\'quemcomprou\']) ) {
foreach ( $_POST[\'quemcomprou\'] as $x_post_id => $value ) {
$data = stripcslashes($value);
$target_post_id = (int)$x_post_id;
update_post_meta( $target_post_id, \'quem_comprou3\', $data);
}
}