Here is the code of my plugin, to add a post meta. The problems are :
after some tests, i figured out that only the "older" posts "copy" the post meta, but not the newest ones. So let's say it is not the main problem i have. (if you have an explanation for this, i'll take it though ;) )
the main problem is now : if i update a meta, it doesn't update it but create a new meta, for the same post_id, same meta_key, and thus same meta_value.
I'm using here the function "save" from the tutorial (above).
add_action( 'add_meta_boxes', 'myplugin_add_custom_box' );
add_action( 'save_post', 'myplugin_save_postdata' );
/* Adds a box to the main column on the Post and Page edit screens */
function myplugin_add_custom_box() {
add_meta_box(
'test1',
__( 'Author : ', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'post'
);
add_meta_box(
'test2',
__( 'My test2', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'movies'
);
}
/* Prints the box content */
function myplugin_inner_custom_box() {
global $post;
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
$met = get_post_meta($post->ID, 'champ', true)? get_post_meta($post->ID, 'champ', true) : 'empty meta';
/* input */
echo '<label for="myplugin_new_field">';
_e("Author name : ", 'myplugin_textdomain' );
echo '</label> ';
echo '<input type="text" id="champ" name="champ" value="'.$met.'" />';
/* select list */
echo '<label for="my_list_field">';
_e("Already in database : ", 'myplugin_textdomain' );
echo '</label> ';
echo '<select name="my_list_field" id="my_list_field">';
global $post;
$s_query = new WP_Query( array(
'suppress_filters' => false,
'post_type' => 'movies'));
while($s_query->have_posts()):$s_query->the_post();
$sname = $post->post_title;
$s_output2 ='';
$s_output2 .= '<option value="'.$post->ID.'" >';
$s_output2 .= $post->post_title.' : allo';
$s_output2 .= '</option>';
echo $s_output2;
endwhile ;
echo '</select>';
wp_reset_query();
}
// Save the Metabox Data
function wpt_save_events_meta($post_id, $post) {
if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
$events_meta['champ'] = $_POST['champ'];
foreach ($events_meta as $key => $value) { // Cycle through the $events_meta array!
$value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
}
}
add_action('save_post', 'wpt_save_events_meta', 1, 2); // save the custom fields