Prefill or pre-select category on contact form 7 (Post My CF7 Form) form

  contact-form-7, jquery, php, wordpress

I am using Post My CF7 Form with Contact Form 7 (wordpress plugins) to be able to allow users to fill in a form and create a post via the front end.

With Post My CF7 Form you have the ability to create a checkbox field or a dropdown menu and map it, the user can then select a category on the form to post to. I would like to pre-fill the category and hide the input field. Hiding it worked by using "hidden" tag as such: [hidden checkbox checkbox-579 exclusive]

The only thing left is pre-selecting or pre-filling the category generated, which I am struggling to do. Either doing it this way or finding a way to change the default category the form posts to, either way works for me, but I just need this form to post to a different category compared to another form I have on a different page.

Within the plugin there are close-to-being-it instructions, the closes one I found was below, but I am not sure if I am simply doing it wrong. I have been looking for a few hours now and stumped. Would appreciate some guidance.

add_filter('cf7_2_post_filter_cf7_taxonomy_terms', 'modify_my_terms',10,4);
/**
* Function to pre-fill form dropdown/radio/checkbox fields mapped to a taxonomy.
* Hooked to 'cf7_2_post_filter_cf7_taxonomy_terms'.
* @param array $terms_id initially an empty array.
* @param $cf7_id  the form id being loaded.
* @param $field  the field name for which the value is being filtered.
* @param string $cf7_key unique key identifying your form.
* @return array an array of term IDs to select.
*/
function modify_my_terms($terms_id, $cf7_id, $field, $cf7_key){
  /*This filter allows you to pre-fill/select taxonomy terms fields for new submissions.*/
  //assuming you have defined a checkbox field called checkbox-579 for cf7 form 'sharelinkform'.
  if('sharelinkform' == $cf7_key & 'checkbox-579' == $field){
    $term = get_term_by('name','London','location_categories'); //not sure about this line, tried various ways, this is default.
    $terms_id = array();
    $terms_id[] = $term->term_id;
  }
  return $terms_id;
}

Full list https://ps.w.org/post-my-contact-form-7/assets/screenshot-8.png?rev=1817912 (if it helps)

Source: Ask PHP

LEAVE A COMMENT