I am trying to add a custom field to all my posts and of course saving/reading the value. As a starting point I took the example from the Wordpress Codex and stripped it down to bare bones. I know it know has serious security flaws, I am just trying to understand it.
The problem I am facing at the moment is that nothing is saved. After looking at what is POSTed when the post is saved, I noticed that the input's key & value is not present in the $_POST
array at all. The property exists in the database, but without value of course.
I also noticed that the variable $post
passed to the add_input
is empty, but I don't why (I guess this is the problem?).
This is the code from my functions.php:
function add_custom_field() {
add_meta_box( 'my_field', 'My Field', 'add_input', 'post' );
}
add_action( 'add_meta_boxes', 'add_custom_field' );
function add_input( $post ) {
$value = get_post_meta( $post->ID, 'my_key', true );
echo '<input type="text" value="' . $value . '" id="my_id">';
}
function save( $post_id ) {
$mydata = sanitize_text_field( $_POST['my_id'] );
update_post_meta( $post->ID, 'my_key', $mydata );
}
add_action( 'save_post', 'save' );
Do you see any errors in the code above? Do you have any comments to my info I gave you? Why is nothing POSTed to the server?
'<input type="text" value="' . $value . '" name="my_id" id="my_id">';
input
needs aname
attribute. id's are for styling/javascriptname value
pairs get sent to$_GET and $_POST
save_post
, you're missing lots of things. Your hook is running in places where it shouldn't.