我在WordPress中创建了一个自定义元框,该框在同一框中包含多个字段。我遇到的问题是,当我在WP管理员中的字段中键入内容时,所做的更改不会保存。
我已经创建了一个保存功能。保存仅适用于仅包含一个字段但不适用于多个字段的元框。
add_action('save_post', 'save_details');
add_action("admin_init", "admin_init");
function admin_init(){
add_meta_box("report-pdf-meta-01", "Report PDF #1", "report_pdf_01", "report", "normal", "high");
}
function save_details(){
global $post;
update_post_meta($post->ID, "report_pdf_01", $_POST["report_pdf_01"]);
update_post_meta($post->ID, "report_pdf_title_01", $_POST["report_pdf_title_01"]);
}
function report_pdf_01(){
global $post;
$custom = get_post_custom($post->ID);
$report_pdf_01 = $custom["report_pdf_01"][0];
$report_pdf_title_01 = $custom["report_pdf_title_01"][0];
?>
<p><label>PDF Field:</label>
<input name="report_pdf_01" value="<?php echo $report_pdf_01; ?>" />
<p><label>Button Title:</label>
<input name="report_pdf_title_01" value="<?php echo $report_pdf_title_01; ?>" /></p>
<?php
}
我认为这将导致字段保存,因为其他框在以相同方式设置一个字段时也保存了,但是到目前为止,情况并非如此。任何帮助将不胜感激!
答案 0 :(得分:0)
您的代码似乎是正确的,但是我建议进行如下修改:
add_action('save_post', 'save_details', 10, 2);
add_action("admin_init", "register_custom_metaboxes"); //renaming the function so as to avoid confusion and conflicts.
function register_custom_metaboxes(){
add_meta_box("report-pdf-meta-01", "Report PDF #1", "report_pdf_01", "report", "normal", "high");
}
function save_details($id, $post_data){
//The $post_data object and current post ID are available to us to begin with.
//Some necessary capabilities check mentioned below.
if (!current_user_can("edit_post", $id)) {
return $post_data;
}
if (defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) {
return $post_data;
}
//Just making sure that we are getting the correct data and to verify the received field names we log it into the file which will be created at the root directory level.
error_log('Posted Data : '.print_r($_POST, true).PHP_EOL, 3, $_SERVER['DOCUMENT_ROOT'] . "/post.log");
//sanitizing the data before saving.
update_post_meta($id, "report_pdf_01", sanitize_text_field($_POST["report_pdf_01"]));
update_post_meta($id, "report_pdf_title_01", sanitize_text_field($_POST["report_pdf_title_01"]));
}
function report_pdf_01(){
global $post;
//Retrieving post meta data by individual key in singular format and not array.
$report_pdf_01 = get_post_meta($post->ID, "report_pdf_01", true);
$report_pdf_title_01 = get_post_meta($post->ID, "report_pdf_title_01", true);
?>
<p><label>PDF Field:</label>
<input name="report_pdf_01" value="<?php echo $report_pdf_01; ?>" />
<p><label>Button Title:</label>
<input name="report_pdf_title_01" value="<?php echo $report_pdf_title_01; ?>"/></p>
<?php
}