WordPress - Add extra column to wp_posts, and post

2019-05-18 11:57发布

I am trying to add an extra field in my Add Post or Add Page, where I insert the value of that field into a manually added column added in the wp_posts table in the database.

I know that I can use Custom Field Templates, but the problem is that these custom fields insert the values into wp_postmeta and not wp_post, and I need everything for the single post in the same table.

Any idea how to do this?

1条回答
对你真心纯属浪费
2楼-- · 2019-05-18 12:58

If you've already manually added the field to the wp_posts table, then you'll just need to use a few hooks to add the field to the posts page and then save it.

// Function to register the meta box
function add_meta_boxes_callback( $post_type, $post ) {
    add_meta_box( 'my_field', 'My Field', 'output_my_meta_box', 'post' );
}
add_action( 'add_meta_boxes', 'add_meta_boxes_callback', 10, 2 );

// Function to actually output the meta box
function output_my_meta_box( $post ) {
    echo '<input type="text" name="my_field" value="' . $post->my_field . '" />';
}

// Function to save the field to the DB
function wp_insert_post_data_filter( $data, $postarr ) {
    $data['my_field'] = $_POST['my_field'];
    return $data;
}
add_filter( 'wp_insert_post_data', 'wp_insert_post_data_filter', 10, 2 );
查看更多
登录 后发表回答