I’m working on a plugin, where I have defined a hook which is supposed to create a custom post field in the admin panel. The code for the same:
//ADDING CUSTOM FIELDS IN ADMIN PANEL
add_action('add_meta_boxes', 'jericho_meta');
add_action('save_post', 'jericho_saved');
function jericho_meta()
{
add_meta_box('jericho_name', 'Favorite PPV', 'jericho_handler', 'post');
}
function jericho_handler()
{
$value = get_post_custom($post->ID);
$namey = esc_attr($value['jericho_name'][0]);
echo '<label for = "jericho_name">Favorite PPV</label><input type = "text" id = "jericho_name" name = "jericho_name" value = "'.$namey.'" />';
}
function jericho_saved()
{
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
{
return;
}
if(!current_user_can('edit_post'))
{
return;
}
if(isset($_POST['jericho_name']))
{
update_post_meta($post_id, 'jericho_name', $_POST['jericho_name']);
}
}
This code generates a custom post field in the admin post panel as shown in the screenshot below:
However, when I enter a value in that text field and click on Update
, the input value never gets saved inside the text field when I try checking the field on refreshing the page.
What seems to be wrong with my code?
EDIT 1:
I have updated my code and added a new action named save_post
and defined its corresponding function. However, the problem seems to be with the way I have defined the input field itself, because when I tried inspecting the text field’s element, this is what I got:
<input type="text" id="jericho_name" name="jericho_name" value>
Based on the code you provided i can see that you are not registering callback/trigger for saving post meta data.
You need to handle this by yourself (will not be handled automaticly).
Currently, what you did is you tied “jericho_handler()” function to render data when post edit page renders. And that works just fine, as it should.
You need to add additional function which will be triggered on ‘save_post’ where you will handle saving data into the database.
Please check detail tutorial over here. Code i pasted above is from this link.
If you are already registering this handler and you are still encountering issues, please update your question with other parts of code as well.