Insights

    How to Automatically Create Tags for Media based on uploaded media's filename in Drupal 10

    Tags
    Code Crunch

    Creating an automated system to generate tags for media files based on their filenames can greatly enhance organisation and accessibility within a Drupal 10 website. This blog will guide you through the process of automatically extracting tags from media filenames and assigning them to media entities using Drupal's functionality.

    In modern content management systems like Drupal 10, tagging media files can improve searchability and categorisation, making it easier for users to find relevant content. Automating the process of creating tags based on filenames can save time and ensure consistency. This also helps in integrating to an external AI based Image processing engines for better SEO and search capabilities.

    Steps to Automatically Create Tags for Media

    • Step 1
      • Create a custom module or use an existing custom module

    name: General Utility

    type: module

    description: 'Utility functions used by the website.'

    core_version_requirement: ^10

    package: Custom 

     

    • Step 2

      • Create an empty .module file for the above module or use the existing custom modules .module file.

       

    • Step 3

      • Update the .module file to implement a presave hook for media entities (hook_ENTITY_TYPE_presave()). This hook will be triggered whenever a media entity is being saved.

    <?php

    use Drupal\media\MediaInterface;

    use Drupal\file\FileInterface;

     

    /**

    * Implements hook_ENTITY_TYPE_presave().

    */

    function module_name_media_presave(MediaInterface $entity) {

      if ($entity && $entity->bundle() == 'image') {

        // Get the file entity associated with the media entity.

        $file = $entity->get('field_media_image')->entity;

     

        // Check if the file entity exists and is valid.

        if ($file && $file instanceof FileInterface) {

          // Get the filename of the file entity.

          $filename = $file->getFilename();

          $keywords = getKeywordsfromImage($filename);

     

          // Load or create taxonomy terms based on the extracted keywords.

          $termIds = [];

          foreach ($keywords as $keyword) {

            // Check if the taxonomy term exists.

            $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties([

              'name' => $keyword,

              'vid' => 'keywords', // Taxonomy machine name

            ]);

     

            // Check if term is found.

            if (!empty($term)) {

              $termId = reset(array_keys($term));

              $termIds[] = $termId;

            } else {

              // Create a new taxonomy term if it doesn't exist.

              $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->create([

                'name' => $keyword,

                'vid' => 'keywords', //Taxonomy machine name

              ]);

              $term->save();

              $termIds[] = $term->id();

            }

          }

     

          // Set the taxonomy term field on the media entity.

          $entity->set('field_keywords', $termIds);

        }

      }

    }

     

    /**

    * Extracts keywords from the image filename.

    *

    * @param string $filename

    *   The filename of the image.

    *

    * @return array

    *   An array of extracted keywords.

    */

    function getKeywordsfromImage($filename) {

      if (!empty($filename)) {

        $filename = explode(".", $filename);

        $keywords = explode("_", $filename[0]);

      }

      return ($keywords) ?? [];

    }

     

    • Step 4

      • For the above code to work, create a taxonomy or tag field in the Image media type to store the keywords processed using the image name. In the above example the field name is "field_keywords" and its linked taxonomy is "keywords".

       

    • Step 5

      • After implementing the code changes, clear Drupal's cache to ensure that the new hook implementation is recognised.

     

    Check out our YouTube video for a live demonstration! [Watch Now]

     

    Conclusion 

    By implementing this solution, Drupal will automatically extract tags from media filenames and assign them as taxonomy terms to media entities. This approach can significantly improve the organisation and searchability of media content within your Drupal 10 website.

    Get in Touch for Expert Drupal Services