You’re already on the right way; just add another loop for the $parent_terms
array around your existing loop. Also it might be a good idea to check if the numbers in the array are valid term IDs, so you might end up doing something like this:
$parent_terms = array( 1, 2, 3, 10 );
$taxonomy = 'products';
echo '<ul>';
foreach ( $parent_terms as $parent_term_id ) {
$parent_term = get_term_by( 'id', $parent_term_id, $taxonomy );
if ( $parent_term ) {
echo '<li><a href="' . get_term_link( $parent_term_id, $taxonomy ) . '">' . $parent_term->name . '</a>';
$child_terms = get_term_children( $parent_term_id, $taxonomy );
if ( $child_terms ) {
echo '<ul>';
foreach ( $child_terms as $child_term_id ) {
$child_term = get_term_by( 'id', $child_term_id, $taxonomy );
echo '<li><a href="' . get_term_link( $child_term_id, $taxonomy ) . '">' . $child_term->name . '</a></li>';
} // end of child terms loop
echo '</ul>';
} // end of $child_terms
echo '</li>';
} // end of $parent_term
} // end of parent terms loop
echo '</ul>';
Update: Assuming you’re using something like OptionTree plugin you can populate the $parent_terms
array like this:
$parent_terms = array(); // define empty array
$term_options = ot_get_option('option-name');
foreach ( $term_options as $term_option_id ) {
// convert strings to numbers and save them in $parent_terms
array_push( $parent_terms, intval($term_option_id) );
}