Search code examples
phpwordpressimageupload

add_post_meta create multiple meta_key


hi i created a upload function but have an issue add_post_meta create multiple meta_key instead of one ...

example :-

meta_key meta_value

_product_image_gallery 1
_product_image_gallery 2
_product_image_gallery 3 

its should be...

meta_key meta_value

_product_image_gallery 1,2,3


if ( $_FILES )

{

    $files = $_FILES['agp_gallery'];

    foreach ($files['name'] as $key => $value)

    {

        if ($files['name'][$key])

        {

            $file = array(

            'name' => $files['name'][$key],

            'type' => $files['type'][$key],

            'tmp_name' => $files['tmp_name'][$key],

            'error' => $files['error'][$key],

            'size' => $files['size'][$key]

            );

        }

        $_FILES = array("agp_gallery" => $file);

        $i=1;

        foreach ($_FILES as $file => $array)

        {

            $newupload = agp_process_wooimage($file,$post_id,$i);

            $i++;

        }

    }

}

and

function agp_process_wooimage($file, $post_id, $count)

{

    if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false();

    require_once(ABSPATH . "wp-admin" . '/includes/image.php');

    require_once(ABSPATH . "wp-admin" . '/includes/file.php');

    require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $attachment_id = media_handle_upload($file, $post_id);

    $post_id = array ();

    $array = array_push($post_id, '_product_image_gallery', $attachment_id);

    update_post_meta($post_id, '_product_image_gallery', $attachment_id);
}

Solution

  • For each loop you call media_handle_upload() and pass a new $file to it. I think this will create a new attachment ID for each file.

    To which you then use in update_post_meta() and this functions defaults to using add_post_meta() if something does not exist. Which it won't because you've not yet added that particular attachment to the post.

    I would see this script is working as intended and your question may be missing something. Are you asking for multiple images to be added to a single meta_value?