Last active
September 5, 2020 14:19
-
-
Save paulmiller3000/eaa11d895b69ba6cb58cfc0169301a3f to your computer and use it in GitHub Desktop.
Get all terms for a taxonomy assigned to a WordPress post, returning them as a comma-delimited string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Use Case: A taxonomy named "Specialty" assigned to a post has several terms. | |
* The user needs to receive them back like this: "landlord representation, real estate, tenant representation". | |
* | |
* Call it like this: | |
* $term_list = bsd_get_taxonomy_terms_as_string( 'bsd-specialty', 1035 ); | |
* Where bsd-specialty is the taxonomy slug and 1035 is the post ID. | |
*/ | |
public function bsd_get_taxonomy_terms_as_string( $taxonomy_name, $object_id ) { | |
$tax_terms = null; | |
$taxonomy_terms = wp_get_object_terms( $object_id, $taxonomy_name ); | |
if ( !$taxonomy_terms ) { | |
return $tax_terms; | |
} | |
if ( isset( $taxonomy_terms->errors ) ) { | |
return $tax_terms; | |
} | |
$i = 0; | |
$array_count = count( $taxonomy_terms ); | |
while ( $i < $array_count ) { | |
if ( !$taxonomy_terms[$i]->name ) { | |
continue; | |
} | |
$tax_name = $taxonomy_terms[$i]->name; | |
if ( $i > 0 ) { | |
$tax_terms = $tax_terms . ', '; | |
} | |
$tax_terms = $tax_terms . $tax_name; | |
$i++; | |
} | |
return $tax_terms; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment