You should avoid creating more tables. Just do it if you really have a good reason to. Note that wp_postmeta
can store practically any kind of data, and simply using the get_post_meta
function can do all the job in most cases.
But if you must use another table, and taking it generally, then you're looking for the save_post
and delete_post
hooks.
Replicating custom fields
Because you mention custom fields, if you want to replicate the information from wp_postmeta
to another table, you would do something like:
add_action('save_post', 'save_markers');
function save_markers($post_id) {
global $wpdb;
$marker = get_post_meta($post_id, 'marker_custom_field', true);
// go and put $marker on the markers table
$wpdb->query("INSERT INTO markers ...");
}
The above applies also for the delete_post
hook.
Metaboxes
But, if you want to store the information directly on the other table, maybe metaboxes suits you better.
add_action( 'add_meta_boxes', 'marker_add_meta_box');
function marker_add_meta_box() {
add_meta_box(
'marker_metabox',
__('Marker Title', 'your-plugin-textdomain'),
'marker_metabox',
'post'
);
}
function marker_metabox ($post) {
wp_nonce_field(plugin_basename( __FILE__ ), 'your-plugin-texdomain');
$marker = get_marker_from_another_table();
?>
<label for="marker_field">
<?php _e('Marker field description', 'your-plugin-texdomain'); ?>
</label>
<input type="text" id="marker_field" name="marker_field" value="<?php echo $marker; ?>" size="25" />
<?php
}
And then, for saving it:
add_action('save_post', 'save_markers');
function save_markers ($post_id) {
if (defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE)
return;
if ('locations' != $_POST['post_type'])
return;
if (!current_user_can( 'edit_post', $post_id ))
return;
/* Here you have $marker and $post_id, then you can just
do the reference in your markers table. */
global $wpdb;
$marker = $_POST['marker_field'];
$wpdb->query("INSERT INTO markers VALUES ...");
}
And of course, you can do more verifications with the code above.