So I'm trying to save the value of a custom term to my database. The table is created as is the custom term. The code below outputs the text field onto my custom terms page but it just doesn't save any value to the database.
Can anyone see if there's anything wrong with this? (I'm sure there's something I've missed)
add_action ( 'movie_edit_form_fields', 'movie_access_metabox' );
add_action ( 'edited_movie', 'save_movie_data' );
function movie_access_metabox($movie) {
global $wpdb;
$value = $wpdb->get_var('select meta_value from wp_termmeta where meta_value='.$movie->meta_value);
?>
<tr>
<th scope="row" valign="top"><label><?php _e('Movie year') ?></label></th>
<td>
<input type="text" id="year" name="year" value="" <?php echo $value ?>>
</td>
</tr>
<?php
}
function save_movie_data($term_id) {
global $wpdb;
$wpdb->termmeta = 'wp_termmeta';
if (isset($_POST['year'])) {
$wpdb->delete('wp_termmeta', array('meta_key' => '_year', 'term_id' => $term_id));
$wpdb->insert('wp_termmeta', array('term_id' => $term_id, ',meta_key' => '_year', 'meta_value' => $value));
}else{
$wpdb->delete('wp_termmeta', array('meta_key' => '_year', 'term_id' => $term_id));
}
}
UPDATE #1:
Failing to manage to get the answer provided by @Oleg Butuzov to work, I have put some more time into my original answer and got it to the stage where it saves the users input to the db. The problem now is that it only seems able to save one value, the value can be updated but only one row can be added at a time. If anyone has any ideas please bring them forward and I will continue to update the code so hopefully can help someone else in future.
UPDATE #2:
*Removed wrong code from post.
It turns out that the main reasons I was only able to add one value was due to the fact I had only used delete
and insert
- no update
and had not used AUTO_INCREMENT
on the create termmeta
schema. Full working answer is provided below.