foreach循环中的Wordpress更新元值

Wordpress in foreach loop updating meta values

我已经完成了 foreach 循环以获得自定义 post 类型到前端。我有一个名为 'order_staatus' 的自定义字段。当我在循环中查看我的前端列表时,我想添加一个按钮,它将把这个 post 'order_staatus' 更改为不同的值..我的代码..

<? foreach ( $postslist as $post ) :
   setup_postdata( $post );
?> 

<div class="profile_order_row">
   <a href="<?php the_permalink(); ?>"> <?php the_author(); ?> <?php the_title(); ?></a>
   <?php
      Global $post;
      if ( isset( $_POST['submit'] ) )
      {   
          if( ! isset( $post ) ) {
              echo 'Post not set';
              die();
          }
          else if( ! isset( $_POST['staatus'] ) && ! empty( $_POST['staatus'] ) ){
          echo 'Error';
          die();
          }

          $postid = $_POST['post_id'];
          update_post_meta($postid,'order_staatus','1');
      }

      $staatus = get_post_meta($post->ID, 'order_staatus', true);

      echo print_r($staatus);
   ?>

   <form method="post" action="">
      <input type="hidden" name="post_id" value="'.$post->ID.'" />
      <input type='text' name='staatus' value='<? echo $staatus ?>' />
      <input type='submit' value='save' />
   </form>

</div>


<?php endforeach; wp_reset_postdata(); ?>

我认为问题不在于函数 update_post_meta。我认为更可能的问题是未设置 $_POST['submit'] 。提交表单时,不会发送提交按钮的值。 value 属性仅用于分配按钮的文本。

我会像这样重写 IF 代码块:

  if ( isset( $_POST ) )
    {   

      if( ! isset( $_POST['staatus'] ) && ! empty( $_POST['staatus'] ) ){
        echo 'Error';
        die();
      }

      $postid = sanitize_text_field($_POST['post_id']);
      update_post_meta($postid,'order_staatus','1');
  }

注意,我删除了 isset($post) 检查,因为你是 运行 foreach ( $postslist as $post ) 中的这段代码,它定义了 $post,因此它将始终在该循环中设置.

我还添加了函数 sanitize_text_field() 来清理 post_id。这是避免 SQL 注入的重要安全措施。所有用户输入,包括 $_POST,都可能包含危险数据,需要在使用前进行清理。

希望对您有所帮助!