我的问题是关于save($postID)
功能。这里有一个参数$postID
,它在函数中用于保存为id。我看到这个$postID
有一个空值。$postID
的实际post id是如何工作的?
This is the simple meta-box code
/* simple meta box */
/* creating field */
add_action('admin_menu', 'my_post_options_box');
function my_post_options_box() {
if ( function_exists('add_meta_box') ) {
add_meta_box('post_header', 'Asif, save me!', 'testfield', 'post', 'normal', 'low');
}
}
function testfield(){
global $post;
?>
<input type="text" name="Asif" id="Asif" value="<?php echo get_post_meta($post->ID, 'Sumon', true); ?>">
<?php
}
/* end of creating field */
/* storing field after pressing save button */
add_action('save_post', 'save');
function save($postID){
if (!defined('DOING_AUTOSAVE') && !DOING_AUTOSAVE) {
return $postID;
}
else
{
if($parent_id = wp_is_post_revision($postID))
{
$postID = $parent_id;
}
if ($_POST['Asif'])
{
update_custom_meta($postID, $_POST['Asif'], 'Sumon');
}
}
}
// saving in postmeta table
function update_custom_meta($postID, $newvalue, $field_name){
if(!get_post_meta($postID, $field_name)){
// create field
add_post_meta($postID, $field_name, $newvalue);
}
else{
//update field
update_post_meta($postID, $field_name, $newvalue);
}
}
你使用了错误的Action Hook
不使用add_action('admin_menu', 'my_post_options_box');
使用add_action('add_meta_boxes', 'my_post_options_box');
add_action('add_meta_boxes', 'my_post_options_box');
function my_post_options_box() {
if ( function_exists('add_meta_box') ) {
add_meta_box('post_header', 'Asif, save me!', 'testfield', 'post', 'normal', 'low');
}
}
您可以查看http://codex.wordpress.org/Function_Reference/add_meta_box以获得详细的概述。
一些问题/答案你可以看看。
- 在Wordpress 中添加多个日期到自定义帖子类型
- 如何在wordpress页面中添加元框
保存文章
动作save_post
自动传递Post ID给回调函数。你可以在你的回调函数中使用。
一些已经回答的问题
- https://wordpress.stackexchange.com/questions/41912/perform-an-action-when-post-is-updated-published
- http://codex.wordpress.org/Plugin_API/Action_Reference/save_post