I would really appreciate any help on my issue, I am not a pro 😉
I created a taxonomy field for a custom post types taxonomy and simply want to display all options with a select dropdown within a custom form I have created (not with acf or a plugin). I used the code I found in the docs here. It works fine with a regular select field, but it is displaying an empty dropdown using the taxonomies field key:
<?php
$field_key = “field_5820f0c21ed72″;
$field = get_field_object($field_key);
if( $field )
{
echo ‘<select name=”‘ . $field[‘key’] . ‘”>’;
foreach( $field[‘choices’] as $k => $v )
{
echo ‘<option value=”‘ . $k . ‘”>’ . $v . ‘</option>’;
}
echo ‘</select>’;
}
?>
Any suggestions? Thanks a lot
The taxonomy field does not have an array of ‘choices’, like the select field does, because the choices are loaded from the database, they are not typed out in the ACF configuration.
You should use a database query for this:
global $wpdb;
$customTaxonomy = 'category';
$sql = "
SELECT
te.term_id,
te.name
FROM $wpdb->terms te
LEFT JOIN $wpdb->term_taxonomy tt
ON tt.term_id = te.term_id
WHERE tt.taxonomy = '$customTaxonomy'
";
$taxonomies = $wpdb->get_results( $sql, ARRAY_A );
if ( $taxonomies ) {
echo '<select name="somename">';
foreach( $taxonomies as $item ) {
echo '<option value="' . $item['term_id'] . '">' . esc_html( $item['name'] ) . '</option>';
}
echo '</select>';
}