The other day, I added meta data of an icon to a custom taxonomy. When you need to add one or two filters to one or two items, it’s simple.
add_filter( 'manage_edit-{my_taxonomy}_columns', 'my_terms_column_header' ); add_action( 'manage_{my_taxonomy}_custom_column', 'my_terms_column_rows', 10, 3 );
Replace {my_taxonomy}
with your taxonomies, call it a day. But when you add in two, or three, or four, you don’t want to make four, or six, or eight lines of code. And when you’re calling the same array over and over, it’s time to get smart.
Make An Array
I originally only want to do this custom work in one taxonomy, so it was no sweat to repeat a little code. But then I realized I wanted to see it in four. Maybe more. So I picked out my array:
$icon_taxonomies = array( 'tax_cliches', 'tax_chartags', 'tax_gender', 'tax_sexuality' );
I made this outside the two functions, because I knew I was going to need it in multiple places. It would necessitate me tossing global $icon_taxonomies;
into every function that needed it, but that was okay. Better that then trying to make sure every time I updated an array, I did it in all the places. Once is better.
Make Your Loop
The easiest thing was to trigger this on admit_init. Grabbing my global, I ran a simple for-loop from that array and added a filter based on the taxonomy named stored in the array:
add_action( 'admin_init', 'my_add_taxonomy_icon_options' ); function my_add_taxonomy_icon_options() { global $icon_taxonomies; foreach ( $icon_taxonomies as $tax_name ) { add_filter( 'manage_edit-'.$tax_name. '_columns', 'my_terms_column_header' ); add_action( 'manage_'.$tax_name. '_custom_column', 'my_terms_column_rows', 10, 3 ); } }
Is It Really Less?
A clever person will count the lines in this code (10 when you add in the variable) and think “Mika, you wrote two extra lines!”
A more clever person will count the lines and think “At 5 taxonomies begins the break even point.”
I know. From the outset it looks like I’m taking more time to over-engineer the solution to a very simple problem. And while I am, I’m also making it easier not to make typos and not to forget a step. I can make one change, one word, and update multiple places becuase that array is also used back in the my_register_taxonomy_metabox()
function.
'taxonomies' => array( 'my_cliches', 'my_chartags' ),
I removed the array and tossed in the new code.
Yes, that’s adding two lines, but it removes my need to think “Where does this all go?” down to one place. And yes, I documented this in-line. The code header has a nice docblock explaining the whole section, what each variable is, and what each function does.