WordPress doesn't save custom meta box
-
Hello
I’m new to wordpress and this is my first post to this forum.
I’m building a simple theme for a virtual computers store. The theme is very simple and it contains a custom post type called “product” to add a new product.
I added a custom meta box the this post type called price to add the price of the product.
The problem is when I save the post (product) or update it the price is not saved to the database.
Here is the code to add the custom meta box for the price:<?php function cp_product_meta_price_box(){ add_meta_box('cp_product_price', __('Price','cptheme'), 'cp_product_meta_price_fields','cp_product', 'side', 'core'); } add_action('add_meta_boxes', 'cp_product_meta_price_box'); function cp_product_meta_price_fields($post){ wp_nonce_field(plugin_basename(__FILE__), 'cp_product_meta_noncename'); $price = get_post_meta($post->ID, 'cp_product_price', true); ?> <p><label for="cp_product_price">Price: </label><input type="text" name="cp_product_price" id="cp_product_price" value="<?php echo esc_attr($price); ?>" ></p> <?php } function cp_product_meta_price_save($post_id, $post){ if(defined('DOING_AUTOSAVE')&& DOING_AUTOSAVE){ return $post_id; } if(!isset($_POST['cp_product_meta_noncename']) || !wp_verify_nonce($_POST['cp_product_meta_noncename'], basename(__FILE__))){ return $post_id; } global $post; $post_type = get_post_type_object($post->post_type); if(!current_user_can($post_type->cap->edit_post, $post_id)){ echo 'ERROR'; return $post_id; } $metadata['cp_product_price'] = (isset($_POST['cp_product_price'])?$_POST['cp_product_price']: ''); // echo "<h1> Price is : $metadata['cp_product_price']</h1>"; foreach($metadata as $key => $value){ $current_value = get_post_meta($post->ID, $key, true); if( $value && '' == $current_value) add_post_meta($post->ID, $key, $value, true); elseif( $value && $value!= $current_value) update_post_meta($post->ID, $key, $value); elseif(''==$value && $current_value) delete_post_meta($post->ID, $key, $current_value); } } add_action('save_post','cp_product_meta_price_save',10,2);Please could you tell me what is the problem in this code. I tried to find the problem for 2 days and found nothing wrong but I don’t know why it’s not working.
Thank you
The topic ‘WordPress doesn't save custom meta box’ is closed to new replies.