Add description to custom taxonomy admin metabox

Looking at the files that create the metabox, there isn’t anything to really hook into that will allow us to add the description so we’ll need to use jQuery. Since the script is extremely small, I’ve opted not to put it into an external file but instead use the admin_footer hook:

/**
 * Prepend taxonomy descriptions to taxonomy metaboxes
 */
function append_taxonomy_descriptions_metabox() {
    $post_types = array( 'page' );          // Array of Accepted Post Types
    $screen     = get_current_screen();     // Get current user screen

    if( 'edit' !== $screen->parent_base ) { // IF we're not on an edit page - just return
        return;
    }

    // IF the current post type is in our array
    if( in_array( $screen->post_type, $post_types ) ) {
        $taxonomies = get_object_taxonomies( $screen->post_type, 'objects' );   // Grab all taxonomies for that post type

        // Ensure taxonomies are not empty
        if( ! empty( $taxonomies ) ) : ?>

            <script type="text/javascript">

              <?php foreach( $taxonomies as $taxonomy ) : ?>

                var tax_slug = '<?php echo $taxonomy->name; ?>';
                var tax_desc="<?php echo $taxonomy->description; ?>";

                // Add the description via jQuery
                jQuery( '#' + tax_slug + 'div div.inside' ).prepend( '<p>' + tax_desc + '</p>' );

              <?php endforeach; ?>

            </script>

        <?php endif;
    }
}
add_action( 'admin_footer', 'append_taxonomy_descriptions_metabox' );

We have a $post_types array to test against so we don’t add this to every post type or every page but only certain pages. We could do the same for taxonomies but I have not in this scenario.


BONUS MATERIAL

The below will add the description to the Admin taxonomy page ( where you add new terms ). We use a much easier hook add_action( '{$taxonomy}_pre_add_form' ):

/**
 * Prepend taxonomy description to Add New Term form
 */
function CollectionTag_admin_edit_description( $tax_slug ) {

    // Grab the Taxonomy Object
    $tax_obj = get_taxonomy( $tax_slug );

    // IF the description is set on our object
    if( property_exists( $tax_obj, 'description' ) ) {
        echo '<h2>Description</h2>';
        echo apply_filters( 'the_content', $tax_obj->description );
    }
}
add_action( 'CollectionTag_pre_add_form', 'CollectionTag_admin_edit_description' );

Leave a Comment