douchen7366 2018-12-05 17:23
浏览 68

使用ajax更新而不是替换wordpress自定义字段

I need updating a custom field in wordpress. I have several images in a gallery with a textarea for comments attached to every single image. Now I'm able to write text in a textarea of an image and the text is saved with ajax instatly after typing in the db. That works. However when adding text to yet another the first text dissapears again. How can I add a second comment without deleting the others?

The entries in the db looks like when adding a comment to the first picture:

a:1:{i:8978;s:20:"Picture Comment no 1";}

When adding a comment to another one the whole entry looks like this:

a:1:{i:8977;s:19:"Picture Comment no2";}

So it overwrites the first one

It needs to look like this:

a:2:{i:8978;s:19:"Picture Comment no1";i:8977;s:19:"Picture Comment no2";}

That's the mySQL db enter image description here

And my code:

if(isset($_POST['method']) && $_POST['method'] == 'comment')
{
    //Get current commentd images
    $current_images_comment = get_post_meta('9550', 'gallery_images_comment', true);

    if(!empty($current_images_comment))
    {
        if ( !in_array( $image_id, $current_images_comment ) ) {
            $current_images_comment[] = $image_id;
        }

       $current_images_comment = array_unique($current_images_comment);

       $poddata = Array( $image_id =>$comm_text );
       update_post_meta('9550', 'gallery_images_comment', $poddata);


    }

}

comm_text contains the text from textarea

if(isset($_POST['comm_text']))
{
    $comm_text = $_POST['comm_text'];
}
  • 写回答

1条回答 默认 最新

  • douhao7677 2018-12-06 02:44
    关注

    Ok, I solved the question with this little code appending new values to the existing array

    $poddata = $current_images_comment;
    $poddata[$image_id] = $comm_text;
    

    Maybe it's useful for someone else, too

    if(isset($_POST['method']) && $_POST['method'] == 'comment')
            {
                //Get current commentd images
                $current_images_comment = get_post_meta($gallery_id, 'gallery_images_comment', true);
    
                if(!empty($current_images_comment))
                {
    
          $poddata = $current_images_comment;
          $poddata[$image_id] = $comm_text;
                } else {
    /*if no entry in db*/
      $poddata = Array(
          $image_id =>$comm_text
          );
    
    }
    
      update_post_meta($gallery_id, 'gallery_images_comment', $poddata);
            }
    
    评论

报告相同问题?