Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save developer-anuragsingh/23752a0183be55c2a818fbc3aff323d4 to your computer and use it in GitHub Desktop.
Save developer-anuragsingh/23752a0183be55c2a818fbc3aff323d4 to your computer and use it in GitHub Desktop.
<?php
$taxoName = "dummy_taxo"; // Taxonomy Name
// Associative array of default arguments for Query
$args = array(
'taxonomy' => $taxoName, // Passed Taxonomy Name
'parent' => 0, // Get only top level terms
'hide_empty' => False // Get all the Terms
);
?>
<form action="" method="post">
<?php
$parentTerms = get_terms($args); // Get all the top level terms
foreach ($parentTerms as $pTerm) { // Passed them in loop to display
echo '<input type="checkbox" name="'. $taxoName .'[]" value="'. $pTerm->term_id .'" />'. $pTerm->name . '<br>';
$args['parent'] = $pTerm->term_id; // Modified previous value of 'parent' KEY to get all the children
$childTerms = get_terms($args);
echo '<ul class="children" id="'.$pTerm->term_id.'" style="display:none;" >';
foreach ($childTerms as $cTerm) {
echo '<li><input type="checkbox" name="'. $taxoName .'[]" value="'. $cTerm->term_id .'"/>'. $cTerm->name .'</li>';
}
echo "</ul>";
}
?>
<input type="submit" name="submit" value="submit">
</form>
<?php
$checkedValues = $_POST[$taxoName]; // Store all the values from checkbox which are "CHECKED"
if(isset($_POST['submit'])) { // If form get submitted
$checkedValues = array_map( 'intval', $_POST[$taxoName] ); // to make sure all values in integers:
$checkedValues = array_unique( $checkedValues );
$result = wp_set_object_terms($post->ID, $checkedValues, $taxoName); // Update all terms in related TAXONOMY
if (is_wp_error($result)) {
$err_msg = $result->get_error_messages(); // Get error message if found
echo $err_msg[0];
}
else {
echo "all terms are updated";
}
}
?>
<style>
ul.children {
list-style: none;
margin-left: 15px;
}
</style>
<script>
jQuery(document).ready(function(){
jQuery('input[type="checkbox"]').click(function(){
var parentValue = jQuery(this).attr("value"); // get the value of parent element
if(jQuery(this).attr("value")== parentValue){
//jQuery("#"+parentValue).toggle(); // doggle child element based on parent value
jQuery("#"+parentValue).fadeToggle( "slow", "linear" ); // doggle child element based on parent value with fadded effect
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment