How to save metabox data with foreach
-
There are two images that I manually put in the database in the table
wp_postmeta
, with the value of the meta key:my-image-for-post
, indicating Of course the id of the post:I can print in the metabox those images that are already in the DB when editing the post. Like this:
$urlsDB =get_post_meta($post->ID,'my-image-for-post', false); foreach ($urlsDB as $url1) { ?> <img src="<?php echo $url1;?>" style="width:200px;" /> <?php };
But I am trying to save the many images that I select in the metabox when editing the post.
I can select images with wordpress image manager and with jquery fill in the urls and insert
name='my_image_URL'
into the input of each selected image:$("#show").after("<input class='upload_image' type='text' size='36' name='my_image_URL' value= " +attachment.url+ " /></br><img src=" +attachment.url+" class='my_image' src='' width='80px'></br>");
Inside the
<div id="show">
displays the selected images and the inputs are filled with the url of each image to be saved.The meta box is working OK, but when I save the post the content changes, but it does not save the metabox images in DB, I tried the two ways below:
1
add_action( 'save_post', function ($post_id) { if (isset($_POST['my_image_URL'])){ $urls = $_POST['my_image_URL']; Foreach ($urls as $url){ $key1_values = get_post_custom_values( 'my-image-for-post', $post_id ); Foreach($key1_values as $value){ update_post_meta($post_id, 'my-image-for-post', $url, $value); } } } });
2nd way I’ve tried
add_action( 'save_post', function ($post_id) { if (isset($_POST['my_image_URL'])){ $urls = $_POST['my_image_URL']; Foreach ($urls as $url){ update_post_meta($post_id, 'my-image-for-post',$url); } } });
But do not save the urls in the
wp_postmeta
table, what can I be doing wrong?Thanks
- The topic ‘How to save metabox data with foreach’ is closed to new replies.