I use WP plugin for submitting posts from frontend. It's a field builder.
Maybe it uses wp_insert_post()
function, I really don't know.
Here I use my custom shortcode, please check here for the code:
function my_custom_shortcode() {
global $wpdb;
$results = $wpdb->get_results( "SELECT city FROM slovak_cities" );
$select = '<select name="city_field">';
$select .= '<option value="-1">- select your city -</option>';
foreach ( $results as $result ) {
$select .= '<option value="' . str_replace( ' ', '_', strtolower( remove_accents( $result->city ) ) ) . '">' . $result->city . '</option>';
}
$select .= '</select>';
return $select;
}
add_shortcode( 'my_shortcode', 'my_custom_shortcode' );
This shortcode creates a dropdown field in post form with many many options. All options inside are generated from database.
This everything is OK and works good.
But I need help with saving this field as custom field to post when post form is submitted. The element has a name attribute named "city_field". This value should be a META KEY of custom field and META VALUE should be one selected option from element.
Can someone help me please? I know that this is related to add_post_meta() or update_post_meta() functions, but how to use them? Are there any action or filter hooks available?
I found two usable hooks wpuf_add_post_after_insert
and wpuf_edit_post_after_update
in the plugin documentation, that solved my problem:
function prefix_update_my_field( $post_id ) {
if ( isset( $_POST['city_field'] ) ) {
update_post_meta( $post_id, 'city_field', $_POST['city_field'] );
}
}
add_action( 'wpuf_add_post_after_insert', 'prefix_update_my_field' );
add_action( 'wpuf_edit_post_after_update', 'prefix_update_my_field' );