plugin development – How to properly use delete_post_meta before add_post_meta?


i’m working with same name meta fields for a custom post. When i’m saving the post I iterate all meta fields in a foreach loop.

I can save all data all right, but here’s the trick, i want to delete all post meta for given keys so it only keeps what’s in the submitted form. But when i run delete_post_meta before iterating the array with add_post_meta it only saves the last array record.

My inputs looks like this, users can add 4 inputs at a time:

enter image description here

My code looks like this, this way i get all posted data:

$woo_os_product_meta['woo_os_produto'] = esc_textarea( $_POST['woo_os_produto']);
$woo_os_product_meta['woo_os_marca'] = esc_textarea( $_POST['woo_os_marca']);
$woo_os_product_meta['woo_os_referencia'] = esc_textarea( $_POST['woo_os_referencia']);
$woo_os_product_meta['woo_os_problemas'] = sanitize_textarea_field( $_POST['woo_os_problemas']);

Then i delete all previous stored data:

delete_post_meta( $post_id, 'woo_os_produto' );
delete_post_meta( $post_id, 'woo_os_marca' );
delete_post_meta( $post_id, 'woo_os_referencia' );
delete_post_meta( $post_id, 'woo_os_problemas' );

Finally i save all form meta:

foreach ( $woo_os_product_meta as $key => $value ) :       
        add_post_meta( $post_id, $key, $value);

When i it do this way, only the data en the last array index is saved, but if i remove all those delete_post_meta, it then create all meta accordingly… what i’m i doing wrong?

Douglas - 3X Web 1 year 2021-09-02T12:45:05-05:00 0 Answers 0 views 0

Leave an answer