Search code examples
phpwordpressimagewordpress-plugin-creation

How can I replace existing image with new one in wordpress in all posts?


I want to create a plugin for WordPress that converts all non-webp images into webp.

I have created a function that takes the file path as an argument and creates a new webp image from that file.

Now I am stuck, how can I replace this old image with a new one in all posts where the old image is used?


Solution

  • You can use filters for this. WordPress uses actions and filters so developers can modify it’s functions. In this case, take a look at get_attached_file and wp_get_original_image_path.

    • get_attached_file returns file path optimised for web use. Docs
    • wp_get_original_image_path returns path to originally uploaded file. Docs

    With both functions, you can use filter to modify their results. In your case, you will change the file extension, if the file requested was compressed before in the requested format and size.

    Registering filter, which should be invoked when get_attached_file function runs could look like this:

    function get_attached_file_callback( $file, $attachment_id ) {
        // modify the file path
        return $file;
    }
    add_filter( 'get_attached_file', 'get_attached_file_callback', 10, 2 );