Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active October 28, 2023 00:14
Show Gist options
  • Save tommcfarlin/6e5445d9d3d45da14fcf to your computer and use it in GitHub Desktop.
Save tommcfarlin/6e5445d9d3d45da14fcf to your computer and use it in GitHub Desktop.
[WordPress] Determine if a given taxonomy term has children or does not have children.
<?php
// First, read the reads
$materials = wp_get_post_terms( get_the_ID(), 'acme_materials' );
foreach ( $materials as $material ) {
if ( count( get_term_children( $material->term_id, 'acme_materials' ) ) > 0 ) {
// The term has children
}
}
<?php
// First, read the reads
$materials = wp_get_post_terms( get_the_ID(), 'acme_materials' );
foreach ( $materials as $material ) {
if ( count( get_term_children( $material->term_id, 'acme_materials' ) ) === 0 ) {
// The term has no children
}
}
@swissspidy
Copy link

Small typo: In the first example, // The term has no children should be // The term has children :)

Besides that, I'd probably just use if ( get_term_children( ... ) ) since this boolean check equals false for an empty array. No need to use count().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment