I need an ajax form with a dropdown in which you can select a taxonomy term, then in the other dropdown you can select children of said term. Form needs to have name, email, subject and message field on top of that.

WordPress AI Code Robot

Create WordPress code snippets for free without a developer!

Chris requested the  following code from my WordPress AI Code Generator.

I need an ajax form with a dropdown in which you can select a taxonomy term, then in the other dropdown you can select children of said term. Form needs to have name, email, subject and message field on top of that.

The robot generated the following code:

Below is a basic concept for how you could set up your AJAX form in WordPress. The specifics may vary depending on your theme, plugins, and other needs.

Please make sure to replace `YOUR_NONCE_FIELD` and `SOME_ACTION_NAME` with appropriate values specific to your application.

“`php
// Ajax function to get the child terms based on parent term selection
add_action('wp_ajax_nm_get_tax_children', 'nm_get_tax_children');
add_action('wp_ajax_nopriv_nm_get_tax_children', 'nm_get_tax_children');

function nm_get_tax_children() {
$parent_term_id = $_POST['parent_term_id'];
$args = array(
'parent' => $parent_term_id,
);

$terms = get_terms('your_taxonomy_name', $args);

echo json_encode($terms);

die();
}

// You would render the form on your page like this:
?>

<form method="post" id="ajax_form">
<label>Name: <input type="text" name="name"/></label>
<label>Email: <input type="text" name="email" /></label>
<label>Subject: <input type="text" name="subject" /></label>
<label>Message: <textarea name="message"></textarea></label>
<label for="taxParent">Select Parent Taxonomy:
<select id="taxParent" name="taxParent">
<!– Populate with Parent Taxonomies –>
</select>
</label>
<label for="taxChild">Select Child Taxonomy:
<select id="taxChild" name="taxChild">
<!– This dropdown will be populated based on "taxParent" selection –>
</select>
</label>
<input type="hidden" name="action" value="SOME_ACTION_NAME">
<?php wp_nonce_field( 'YOUR_NONCE_FIELD' ); ?>
<input type="submit" value="Submit">
</form>

<script type="text/javascript">
jQuery(document).ready(function ($) {
$(document).on('change', '#taxParent', function () {
var data = {
action: 'nm_get_tax_children',
parent_term_id: this.value
};

$.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function (response) {
//Update '#taxChild' options based on 'response'
});
});
});
</script

More
CODE SNIPPETS