I am trying to have a form save the post taxonomy when the form is saved. The taxonomy slug is passed to the form via an URL parameter.
I created a generic form field to grab the taxonomy slug from the urlparam.
[cred_generic_field type='textfield' field='gen-doc-type' urlparam='doc-type-slug']
{
"required":0,
"default":""
}
[/cred_generic_field]
I then added the following function to be triggered on the form being saved.
add_action('cred_save_data', 'set_doc_type_tax',10,2);
function set_doc_type_tax($post_id, $form_data)
{
// if a specific form for adding doc to hiring checklist form 5271
if ($form_data['id']==5271)
{
$taxfield = $form_data["gen-doc-type"]; // get taxonomy term slug from generic field
$taxslug = 'document-type'; // taxonomy slug for worker document type
wp_set_post_terms( $post_id, $taxfield, $taxslug );
}
}
Nothing is being saved in the taxonomy and I can't figure out why.
Hello,
Please check our document:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data
There isn't such a parameter: $form_data["gen-doc-type"].
In your case, I suggest you try with PHP global POST variable, for example:
replace this line from:
$taxfield = $form_data["gen-doc-type"];
To:
$taxfield = $_POST["gen-doc-type"];
More help:
hidden link
Thanks for the suggestion. I updated my code to the following:
add_action('cred_save_data', 'set_doc_type_tax',10,2);
function set_doc_type_tax($post_id, $form_data)
{
// if a specific form for adding doc to hiring checklist form 5271
if ($form_data['id']==5271)
{
$taxfield = $_POST["gen-doc-type"]; // get taxonomy term slug from generic field
$taxslug = 'document-type'; // taxonomy slug for worker document type
wp_set_post_terms( $post_id, $taxfield, $taxslug );
}
}
I added code to write the $taxfield and $taxslug to the error log and I can see they are the correct values. It appears wp_set_post_terms isn't setting the taxonomy. Do you have a suggestion?
I found a solution. I changed it so wp_set_post_terms uses the ID not the SLUG. I found this suggestion in another support article here https://toolset.com/forums/topic/copy-post-taxonomy-value-to-another-taxonomy-on-cred-save/.
So the following code worked for me.
[php]
add_action('cred_save_data', 'set_doc_type_tax',10,2);
function set_doc_type_tax($post_id, $form_data)
{
// if a specific form for adding doc to hiring checklist form 5271
if ($form_data['id']==5271)
{
error_log("gen-doc-type=".$_POST["gen-doc-type"]);
$taxfield = $_POST["gen-doc-type"]; // get taxonomy term slug from generic field
$taxfield_term = get_term_by('slug', $taxfield, 'document-type');
$taxfield_id = $taxfield_term->term_id;
$taxslug = 'document-type'; // taxonomy slug for worker document type
wp_set_post_terms( $post_id, $taxfield_id, $taxslug );
}
}
My issue is resolved now. Thank you!
Thanks for sharing the solutions.