To be clear I’m not talking about getting the category within a loop. I just want to display a legend in the sidebar so users know which color corresponds to which category.
You can use the function $EM_Taxonomy_Terms->get() to get a list of EM_Taxonomy_Term objects. You can call $EM_Taxonomy_Term->get_color() to the the color and $EM_Taxonomy_Term->get_name() to get the name. Here’s an example of some html that would output the category name with the text color matching the category color:
$output = "<ul>";
$terms = $EM_Taxonomy_Terms->get();
foreach ($terms as $term) {
$output .= '<li style="color:' . $term->get_color() . '">' . $term->get_name() . '</li>';
}
$output .= "</ul>";
echo $output;
Here’s another example of a legend (with the help of ChatGPT). Add the following CSS:
/* Add some basic styling for better presentation */
.legend {
display: flex;
flex-direction: column;
font-family: Arial, sans-serif;
margin-left: 20px;
}
.legend-item {
display: flex;
align-items: center;
margin-bottom: 5px;
}
.legend-item div {
width: 20px;
height: 20px;
margin-right: 5px;
}
Then use the following PHP code to display the legend:
// Define legend items with their colors
$terms = $EM_Taxonomy_Terms->get();
echo '<div class="legend">';
foreach ($terms as $term) {
echo '<div class="legend-item">';
echo '<div style="background-color: ' . $term->get_color() . ';"></div>';
echo '<span>' . $term->get_name() . '</span>';
echo '</div>';
}
echo '</div>';
-
This reply was modified 7 months, 4 weeks ago by joneiseman.
$EM_Taxonomy_Terms
is undefined and it doesn’t seem to be a global variable. Do you know how to access it?
Ended up just having to directly query the database for this but if there’s an official helper function or something please let me know.
Here’s the corrected code:
$output = '<ul>';
$terms = EM_Categories::get();
foreach ($terms as $term) {
$output .= '<li style="color:' . $term->get_color() . '">' . $term->name . '</li>';
}
$output .= '</ul>';
echo $output;
-
This reply was modified 7 months, 3 weeks ago by joneiseman.
-
This reply was modified 7 months, 3 weeks ago by joneiseman.
Ah okay thanks, this seems to work. Cheers!
For anyone else, you can also use get_terms()
arguments with this, for example:
$terms = EM_Categories::get( array( 'hide_empty' => true ) );