Support

Account

Home Forums ACF PRO Front end post update post meta

Solved

Front end post update post meta

  • Hello,

    I created a front end form, whitch looks like this:

    <?php 
    $new_post = array(
     'post_id' => 'new',
     'field_groups' => array(57),
     'form' => true,
     'return' => '%post_url%',
     'html_before_fields' => '',
     'html_after_fields' => '',
     'submit_value' => 'Submit Post',
     'updated_message' => 'Saved!'
     );
     acf_form( $new_post );
    ?>
    
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        var ajaxUrl = "SITE_ADMIN_URL/admin-ajax.php";
    	$(".acf-button").on("click",function(){ // When btn is pressed.
    	var selected_model = $("#acf-field-area option:selected").text();
    		if(selected_model ){
    			$.post(ajaxUrl, {
    					action:"the_model",
    					selected_model: selected_model
    	        });
    		}
        });
    });
    </script>

    In functions.php i have added the following function:

    add_filter('acf/save_post', 'add_car_model', 20);
    
    function add_car_model($post_id) {
      $post_type = get_post_type($post_id);
      if ($post_type != 'cars') {
        // not our post type, bail early
        return;
      }
     
     
            $selected_model = $_POST['selected_model'];
            add_post_meta($post_id, 'car_model', '');
            update_post_meta($post_id, 'car_model', $selected_model);
    
    }

    I have a select dropdown called Make, and based on the make, i am loading values into Model dropdown, which is custom dropdown.

    Using javascript, i managed to get the correct model value(tested it using on change and alert();) but i do not know how to pass the model value into the post’s meta data.

    Thank you for looking into this!

  • Have you actually tried to dump $_POST ? You then would have seen the contents and would have seen that $_POST[‘selected_model’] does not exist.

    To retrieve a posted value, you need to look into $_POST[ ‘acf’ ]. In it you will find the field keys (not the names).

    So you need to check what the field key is for your field.

    Then do something like this:

    if ( ! empty( $_POST[ 'acf' ][ 'field_5a0de683a21cf' ] ) {
        update_post_meta($post_id, 'car_model', 'field_key' );
    }
  • Thank you!

    I forgot to mention that the MODEL field was not a ACF field. I have added the MODEL field a acf-field_xxxx identifier, and now it works as intended.

    Thank you for taking your time to answer me!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.