if(isset($_POST['_item_stock']) && !empty($_POST['_item_stock'])) update_post_meta($post_id, '_item_stock', sanitize_text_field($_POST['_item_stock'])); else delete_post_meta($post_id, '_item_stock');
I do this because if I need more control over validation, I have it. It’s organized and nice looking in the code. The Drawback being that it’s lengthy and it saves each meta individually in the database.
My other option is to standardize all my meta into an array then serialize it. The Drawback to this method is that I can’t run any meta queries on serialized data, so filtering searches or post ordering is out the window.
The final option is to do half and half, serialize what I don’t need for queries and everything else I save individually. While it may be save some overhead I don’t want it to look messy in my code or have any kind of disconnect.
My question is – How do you normally handle posts that have many meta keys? Is the database overhead as bad as I imagine when I save each meta key individually? Which method do you think is the best and why?
You are facing an XY Problem. The only reason to save meta values each as a single row, would be if you need them to be searchable. If you need specific sanitization rules, use either
filter_var_array() or sanitize the values, then build the array and finally save the value.
Gist with a comprehensive