现在的需求是,每篇文章我都有一个固定的字段,就如同文章标题一样是不可或缺的,那么你可以参考我下面的代码(这里以添加两个固定字段keywords和description为例,多个依此类推),将以下代码添加到主题的functions.php中即可:
/* Define the custom box,适用WP 3.0以后的版本 */
add_action( 'add_meta_boxes', 'ludou_add_custom_box' );
// 如果是WP 3.0之前的版本,使用以下一行代码
// add_action( 'admin_init', 'ludou_add_custom_box', 1 );
/* Do something with the data entered */
add_action( 'save_post', 'ludou_save_postdata' );
/* Adds a box to the main column on the Post and Page edit screens */
function ludou_add_custom_box() {
add_meta_box(
'ludou_sectionid',
'SEO', // 可自行修改标题文字
'ludou_inner_custom_box',
'post'
);
}
/* Prints the box content */
function ludou_inner_custom_box( $post ) {
global $wpdb;
// Use nonce for verification
wp_nonce_field( plugin_basename( __FILE__ ), 'ludou_noncename' );
// 获取固定字段keywords和description的值,用于显示之前保存的值
// 此处wp_posts新添加的字段为keywords和description,多个用半角逗号隔开
$date = $wpdb->get_row( $wpdb->prepare( "SELECT keywords, description FROM $wpdb->posts WHERE ID = %d", $post->ID) );
// Keywords 字段输入框的HTML代码
echo '<label for="keywords_new_field">Keywords</label> ';
echo '<input type="text" id="keywords_new_field" name="keywords_new_field" value="'.$date->keywords.'" size="18" />';
// description 字段输入框的HTML代码,即复制以上两行代码,并将keywords该成description
echo '<label for="description_new_field">Description</label> ';
echo '<input type="text" id="description_new_field" name="description_new_field" value="'.$date->description.'" size="18" />';
// 多个字段依此类推
}
/* 文章提交更新后,保存固定字段的值 */
function ludou_save_postdata( $post_id ) {
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['ludou_noncename'], plugin_basename( __FILE__ ) ) )
return;
// 权限验证
if ( 'post' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
// 获取编写文章时填写的固定字段的值,多个字段依此类推
$keywords = $_POST['keywords_new_field'];
$description = $_POST['description_new_field'];
// 更新数据库,此处wp_posts新添加的字段为keywords和description,多个根据你的情况修改
global $wpdb;
$wpdb->update( "$wpdb->posts",
// 以下一行代码,多个字段的话参照下面的写法,单引号中是字段名,右边是变量值。半角逗号隔开
array( 'keywords' => $keywords, 'description' => $description ),
array( 'ID' => $post_id ),
// 添加了多少个新字段就写多少个%s,半角逗号隔开
array( '%s', '%s' ),
array( '%d' )
);
}
保存之后,需要给wp_posts表添加字段keywords和description
如果你想在读取固定字段keywords和description的值,可以使用wpdb类的get_row方法,示例代码:
global $wpdb;
// $post->ID是文章id,自行修改
$date = $wpdb->get_row( $wpdb->prepare( "SELECT keywords, description FROM $wpdb->posts WHERE ID = %d", $post->ID) );
// keywords值
$keywords = $date->keywords;
// description值
$description = $date->description;