Update postmeta as array

Back to Blog

Update postmeta as array

Update postmeta as array is poorly documented but using our code as below makes it simple to create a simple post meta that stores multiple values as an array.

// Values from my form which contains multiple productIDs and values for each productIDs postmeta. Posted as multiple arrays in one operation.
$message_specific = isset( $_POST['message_specific'] ) ? $_POST['message_specific'] : '';

if ( is_array( $message_specific ) ) { // Checking if array
	foreach( $message_specific as $keys => $value ) {
		$parts = explode( '|', $keys ); // Separating the productID from the meta value.
		$settings = get_post_meta( $parts[0], '_message_specific', true ); // Get the stored postmeta value, if any.
		if ( empty( $settings ) ) $settings = array(); // If no postmeta or postmeta is empty create an array.
		$settings[$parts[1]] = $value; // Generate the new values for the postmeta.
		if ( $value  ) {
		update_post_meta( $parts[0], '_message_specific', $settings ); // Update postmeta with the new values as array.
		} else {
		delete_post_meta( $parts[0], '_message_specific' ); // If no values posted just delete any empty postmeta.

Example from our form used with the above code:

<input name="message_specific[<?php echo $product->get_id(); ?>|amount]" id="message_specific[<?php echo $product->get_id(); ?>|amount]" min="0" max="100" value="<?php if ( isset( $specific['amount'] ) ) echo $specific['amount']; ?>" type="number"><br />
<textarea class="text" name="message_specific[<?php echo $product->get_id(); ?>|message]" id="message_specific[<?php echo $product->get_id(); ?>|message]" rows="1"><?php if ( isset( $specific['message'] ) ) echo $specific['message']; ?></textarea>

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Blog


Our store at https://www.arctic-fritid.no takes all our time and therefore we have chosen to close down and sell our website here at arctic-solutions.no.

If you are interested in this website and / or our domains related to this website, please contact us by e-mail or phone +47 40010034.

If you need better web hosting or excellent plugins for your WooCommerce online store, check out our sponsored ads below. 24/7-365 Outstanding support.