plugins – How to save mediaupload multiple files in meta?

Question

I want to add multiple images to meta. I am able to save single files successfully. I am not sure how to add multiple files to meta.

The single image mediaupload works fine. below is the code for it. The multiple mediaupload works fine in the backend editor. I don’t know how to save and retrieve(in php) multiple image paths in meta. Can anyone please help or guide me in the right direction?

attributes that save the meta values for a single image.

p_mediaURL: {
        type: "string",
        default: "",
        meta: "_duib_p_mediaURL",
        source: "meta",
    },
    p_mediaID: {
        type: "integer",
        default: null,
        meta: "_duib_p_mediaID",
        source: "meta",
        default: "",
    },

In edit function:

    const onSelectImage = (media) => {
        setAttributes({
            p_mediaURL: media.url,
            p_mediaID: media.id,
            mediaAlt: media.alt,
        });
    };

Mediaupload component

<MediaUpload
    onSelect={onSelectImage}
    allowedTypes="image"
    value={p_mediaID}
    render={({ open }) => (
    <Button className="is-primary mt-3" onClick={open}>
    Open Media Library
    </Button>
    )}
/>

Mediaupload component for multiple images that works in editor.

<MediaUpload
    onSelect={(gallery) => {
    props.setAttributes({ gallery});
    }}
    type="image"
    multiple
    value={props.attributes.gallery}
    render={({ open }) => (
    <Button className="button button-large" onClick={open}>
        Select Images
    </Button>
    )}
/>

The register_meta function is

function _duib_p_addimages_register_post_meta() {
register_meta(
    'post',
    '_duib_p_addimages',
    [
        'auth_callback' => '__return_true',
        'default'       => __( '', '_duib_p_addimages' ),
        'show_in_rest' => array(
        'schema' => array( 
            'type'  => 'array', 
            'items' => array( 
                'type' => 'integer' 
            )
        )
            ),
        'single'        => true,
        'type'          => 'string',
        'object_subtype' => 'properties',
    ]
);
}
add_action( 'init', '_duib_p_addimages_register_post_meta' );

The sample json output is

"meta": {
 
  "_duib_p_mediaURL": "http://localhost/property/wp-content/uploads/2022/12/hele_03.jpg",
  "_duib_p_description": "",
  "_duib_p_addimages": [
    
  ]
},

0
Mangesh Yadav 1 month 2022-12-27T13:48:13-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse