WordPress media library : Add custom taxonomy with quick edit in list view

Posted on by Chandan

Introduction: WordPress is a versatile platform that allows users to create, manage, and display content seamlessly. In this blog post, we will explore how to elevate your WordPress media library by incorporating a custom taxonomy, all achieved through the use of a plugin and code enhancements. Our goal is to introduce a new column in the media library for assigning custom taxonomy terms and enabling quick edits directly from the list view.

Step 1: Creating a Custom Taxonomy with Custom Post Type UI Plugin

Before diving into code, let’s simplify the creation of a custom taxonomy using the “Custom Post Type UI” plugin. This plugin provides a user-friendly interface to define custom post types, taxonomies, and more.

  1. Install and Activate the Plugin:
    • Navigate to the WordPress dashboard.
    • Go to “Plugins” > “Add New.”
    • Search for “Custom Post Type UI” and install it.
    • Activate the plugin.
  2. Create a Custom Taxonomy:
    • Find the “CPT UI” menu in the dashboard.
    • Select “Add/Edit Taxonomies.”
    • Set the taxonomy name, label, and other settings.
    • Save the taxonomy.

With this plugin, you’ve effortlessly added your own taxonomy, and WordPress now recognizes your new classification system.

Here is the complete code that you have to paste into your theme’s functions.php :

view the complete gist

Step 2: Adding Custom Columns to the Media Library Table

We have our taxonomy, let’s proceed to enhance the media library. The first step involves adding a new column labeled ‘Assign Media Category.’ This is achieved through code.

This code is a snippet in PHP for WordPress, a popular content management system. It modifies the columns displayed in the list view table, allowing you to add your columns.

The function custom_media_columns takes an array of existing columns as a parameter, typically provided by WordPress. Inside the function, a new column named ‘assign_media_category’ is added to the array with the label ‘Assign Media Category’. This effectively extends the default set of columns with yours.

The add_filter function is then used to hook this added column into the media library. The ‘manage_media_columns’ filter is employed, which allows you to modify the columns displayed in the admin panel table list view quick edit. It takes two parameters: the first one is the name of the filter, and the second one is the callback function (custom_media_columns in this case) that WordPress should execute when the filter is applied.

Once this code is added to your theme’s functions.php file or a demo pluginyou are writing in , you’ll see a new column named ‘Assign Media Category’ in your media-library table.

Step 3: Populating the Custom Column with Data

The next task is to populate our new column with relevant data. The function custom_media_column_content fetches and displays the taxonomy terms associated with each attachment post type item.

This function utilizes WordPress functions to retrieve the taxonomy terms, presenting users with a checkbox interface for convenient assignment or modification.

The primary purpose is to provide a more organized and categorized view within the library.

The main function, custom_media_column_content, is triggered when WordPress processes the attachment’s post lists columns. It dynamically generates content for the column by fetching and organizing the associated categories of a specific post-type attachment item. The presentation is organized in an accordion-style user interface, making it user-friendly.

Let’s break it down step by step:

  1. Category Retrieval:
    • The code uses get_the_terms to retrieve the categories associated with the current attachment post’s item.
  2. Top-Level Categories:
    • It fetches the top-level categories for your tax-slug and generates checkboxes for each, allowing users to select the appropriate categories.
  3. Recursive Nesting:
    • The code employs a recursive function, nest_terms, to handle the nesting of child categories within the top-level ones. This ensures a hierarchical structure for better organization.
  4. Accordion UI:
    • The generated HTML includes an accordion with a title, ‘Update Media Categories,’ and a content section displaying the category checkboxes. This provides a collapsible and expandable interface for a cleaner user experience.
  5. Save Button:
    • A ‘Save’ button is included within the accordion to allow users to save their category assignments.
  6. Hooking into WordPress:
    • The entire functionality is hooked into the list view (for quick edit) column processing through the ‘manage_media_custom_column’ action. This ensures that the new column is appropriately handled when rendering the post-list table.

In summary, this code introduces a feature that empowers users to categorize their attachment posts more effectively. The UI enhancements, including an accordion and checkboxes, make the process intuitive and user-friendly. The code is flexible and can accommodate both top-level and nested categories, providing a seamless experience for managing post content in WordPress.

 

Step 4: AJAX for Quick Edits

To enable quick edits without leaving the media library page, we utilize AJAX. The save_post_data function handles the AJAX request, updating the selected custom tax terms for a specific image/video/documents

This WordPress code sets up an AJAX action to handle the asynchronous updating of media categories for a post. It includes a function, save_post_data, which performs the following:

  1. Nonce Verification:
    • Checks the nonce (a security token) to ensure that the AJAX request is legitimate and not forged.
  2. Data Processing:
    • If the nonce is valid, the function retrieves and sanitizes the post ID and the selected media category term IDs from the AJAX request.
  3. Update Post:
    • Uses wp_set_post_terms to update the post with the new taxonomy terms.
  4. JSON Response:
    • Sends a JSON-encoded response indicating whether the update was successful ('success' => true) or if the nonce verification failed ('success' => false, 'message' => 'Nonce verification failed.').
  5. Exit Statement:
    • Ensures that only the JSON response is sent back in the AJAX request, preventing any additional output that might interfere with the response.

So, this code creates a secure and efficient mechanism for updating the custom taxonomy of a post using AJAX. The nonce verification adds a layer of security to prevent unauthorized requests. The JSON response communicates the success or failure of the update operation, providing a smooth and responsive user experience when managing custom taxonomies in WordPress.

Step 5: Enhancing User Interface with JavaScript and Styles

For an enhanced user interface, we include styles for a visually appealing accordion layout. This layout organizes and presents the taxonomy terms efficiently.

This code is designed to enhance the user interface for managing taxonomies in the WordPress admin panel. It accomplishes this by injecting a script and styles into the admin footer. The primary features include:

  1. Accordion Interface Styling:
    • Custom styles are applied to create a visually appealing accordion-style interface for media categories. These styles define the appearance of accordion titles, the overall accordion container, and the indentation for child terms.
  2. JavaScript Functionality:
    • The script, written in jQuery, provides interactive behavior for the accordion interface.
    • Initially, it hides the content of the accordion.
    • It sets up a click event for accordion titles, allowing users to toggle the visibility of associated content.
    • A click event is also attached to a button with the class .button.xyz. This button triggers an AJAX request to update media categories for a specific post.
    • The AJAX request includes the post ID, selected tax term IDs, and a security nonce for verification.
  3. AJAX Handling:
    • The server-side AJAX handler, associated with the action ‘save_post_data’, verifies the nonce for security.
    • If the nonce is valid, it processes the AJAX request by updating the post with the selected media category term IDs.
    • It returns a JSON-encoded response indicating the success or failure of the update.
  4. Response Handling:
    • On the client side, the script handles the AJAX response.
    • If the update is successful, it displays an alert notifying the user that the data has been saved.
    • In case of failure, it alerts with an error message, providing feedback on the outcome.
  5. WordPress Action Hook:
    • The entire script and styles are hooked into the ‘admin_footer’ action, ensuring that they are output in the footer of the WordPress admin panel.

Conclusion:

By combining the simplicity of the “Custom Post Type UI” plugin with targeted code enhancements, you’ve successfully transformed your WordPress media library. The addition of a custom taxonomy column, coupled with quick edit functionality, empowers users to manage assets like images, pdfs, zips, and other documents with unprecedented ease. This showcases the adaptability and extendability of WordPress, allowing you to tailor your content management system to meet your specific needs.

About Chandan

Author View all posts by Chandan →

One Response to WordPress media library : Add custom taxonomy with quick edit in list view

  • Rudy says:

    Really nice work. Keep adding blogs like this

  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    *

    *