Change file name from wp_generate_attachment_metadata

I’m pretty new and just have a hang on how wordpress data flows internal.

I am confronted with applying a b/w filter on upload. no problem. I found the wp_generate_attachment_metadata filter and applied a function to it.

With ACF I have 2 fields: grayscale_image to check if I the mode is enabled and no_filter_suffix I regex check if it is present somewhere.

Now the problem: I want to remove the no_filter_suffix to have nice looking file names.

Now I have 2 questions:
– How can I remove the suffix (or slug) and still apply/not apply the b/w filter?
– Is this a (in wordpress manner) good way of doing so? This is a theme feature, though. I am not allowed to create a plugin for it. But I am allowed to use a plugin, if it fits the criteria.

Additional:

Only the admin is allowed to change the flag and knows about the flag. Everyone else is forced to have the b/w filter applied on uploading images.

My filter function:

add_filter('wp_generate_attachment_metadata', 'themename_bw_filter');
function themename_bw_filter($meta)
{
    if (get_field('grayscale_image', 'option')) {
        $path = wp_upload_dir(); // get upload directory
        $file = $path['basedir'] . "https://wordpress.stackexchange.com/" . $meta['file']; // Get full size image

        // Check for "no filter" tag
        if (preg_match('/^.*' . get_field('no_filter_suffix', 'option') . '.*$/', $meta['file'])) {
            // Remove it anyway.
            $pregMatch="https://wordpress.stackexchange.com/" . get_field('no_filter_suffix', 'option') . "https://wordpress.stackexchange.com/";
            $meta['file'] = preg_replace($pregMatch, '', $meta['file']);

            // Only allowed for admin level
            if (is_admin()) {
                return $meta;
            }
        }

        $files[] = $file; // Set up an array of image size urls

        foreach ($meta['sizes'] as $size) {
            $files[] = $path['path'] . "https://wordpress.stackexchange.com/" . $size['file'];
        }

        foreach ($files as $file) { // iterate through each image size

            // Convert image to grayscale credit to http://ottopress.com/2011/customizing-wordpress-images/

            list($orig_w, $orig_h, $orig_type) = @getimagesize($file);
            $image = wp_load_image($file);
            imagefilter($image, IMG_FILTER_GRAYSCALE);
            imagefilter($image, IMG_FILTER_GRAYSCALE, 100, 100, 0);
            switch ($orig_type) {
                case IMAGETYPE_GIF:
                    imagegif($image, $file);
                    break;
                case IMAGETYPE_PNG:
                    imagepng($image, $file);
                    break;
                case IMAGETYPE_JPEG:
                    imagejpeg($image, $file);
                    break;
            }
        }
    }

    return $meta;
}

The solution is inspired by a blog entry of ottopress. Credits given.

0

Leave a Comment