Home > Article > Backend Development > Implementation of PHP function to add categories and tags to media files in WordPress, _PHP tutorial
Media files uploaded from the WordPress backend media library cannot be assigned categories and tags like articles. , but many times we need such functions, such as some download sites, picture sites, etc.
Original state of media editing page
Obviously, in the media editing page in the WordPress backend, there are no categories and tags for you to choose by default.
Add categories to media files
Add the following php code in functions.php of the current theme:
function ludou_add_categories_to_attachments() { register_taxonomy_for_object_type( 'category', 'attachment' ); } add_action( 'init' , 'ludou_add_categories_to_attachments' );
Save and upload functions.php, refresh the media editing page, and you will see an additional category directory in the right column:
Add tags to media files
Add the following code in functions.php of the current theme:
function ludou_add_tags_to_attachments() { register_taxonomy_for_object_type( 'post_tag', 'attachment' ); } add_action( 'init' , 'ludou_add_tags_to_attachments' );
Save and upload functions.php, refresh the media editing page, you will see an additional tab bar in the right column:
At the same time, on the multimedia list page, categories and tags for displaying media are also added. Similarly, there are two submenus under the multimedia menu on the left column: category directory and tag:
Okay, adding categories and tags to media files is as simple as that. We can combine the code added above into the code below, which is more concise and efficient:
function ludou_add_categories_tags_to_attachments() { register_taxonomy_for_object_type( 'category', 'attachment' ); register_taxonomy_for_object_type( 'post_tag', 'attachment' ); } add_action( 'init' , 'ludou_add_categories_tags_to_attachments' );
Another way
In fact, there is another way to achieve this, and you can add independent categories to multimedia without having to mix article categories, and the multimedia list page in the WordPress backend can visually display the media categories.
To use, also add php code in functions.php of the current theme:
function ludou_create_media_category() { $args = array( 'label' => '媒体分类', 'hierarchical' => true, 'show_admin_column' => true, 'show_ui' => true, 'query_var' => true, 'rewrite' => true, ); register_taxonomy( 'attachment_category', 'attachment', $args ); } add_action( 'init', 'ludou_create_media_category' );
If you are not opposed to using plug-ins, we recommend this plug-in: Media Library Categories, which can batch modify the categories of media files.