wordpress给文章添加自定义字段

默认的字段一般是不满足用户自定义的使用的,wordpress给文章添加自定义字段对网站内容的一种扩充,WordPress虽然已经提供了一些常用的字段,但是这样还远远不们满足我们的需求,比如系统参数字段如:备案号、统计代码、版权所有和缩略图字段已经常用的TDK(标题,关键词,描述)字段等;你可以根据你的wordpress主题需要自定义出一系列的其他信息来满足我们网站的功能需求,下来就我们来把默认发布文章时候的字段来添加两个字段,分别为关键词和关键词描述字段,效果如下图

wordpress添加自定义字段

//这里用于创建添加的新字段
add_action( 'add_meta_boxes', 'hx_add_custom_box' );

//这里用于保存新添加的字段,是指发布文中的时候保存到数据库中
add_action( 'save_post', 'hx_save_postdata' );

/* Adds a box to the main column on the Post and Page edit screens */
function hx_add_custom_box() {
    add_meta_box(
        'add_field_group',
        '扩展字段', // 这是扩展字段组的名称
        'hx_inner_custom_box',
        'post'
    );
}

/* Prints the box content */
function hx_inner_custom_box( $post ) {
    global $wpdb;

    // Use nonce for verification
    wp_nonce_field( plugin_basename( __FILE__ ), 'hx_add_field_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 hx_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['hx_add_field_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' )
    );
}
我爱主题网 自2012
主题:260+ 销售:1000+
兼容浏览器

电话咨询

7*12服务咨询电话:

133-7205-6573

微信咨询