Hook for Custom Rop in Wordpress

Asked

Viewed 55 times

4

I have a function that detects the position of the face of the person in an image and returns the X, Y, W, H or she can return the image cropped from the face.

I need to display a photo of a person and I’m currently doing:

<?= wp_get_attachment_image( 1497, 'custom-small-thumb' ) ?>

Right, it displays the photo using the classic Wordpress resize/cut function.

BUT what I REALLY NEED is to display only the face that appears in this image, and I did not want to gambiarra, I would like to use the maximum features of Wordpress for this purpose.

I have a function faceDetector($imagesrc) and I wonder if there’s any hook I can make to run the faceDetector before the wp_get_attachment_image.

In fact i would like much of something like

<?= wp_get_attachment_image ( 1497, 'face-small-thumb' ) ?>

But WP does not let us pass a custom function on add_image_size.

1 answer

1

I see two possibilities, one is the filter wp_get_attachment_image_src and the other wp_get_attachment_image_attributes. The first is applied as soon as the image references are searched in the database (i.e., in all image calls), the second just before the end of the Markup that will be returned by wp_get_attachment_image().

In both the first parameter is an array in which one of the elements is the src (index 0 or 'src') that can be manipulated and returned in a new array.

Example:

<?php 
    add_filter( 'wp_get_attachment_image_src', 'detectFace' );

    function detectFace( $image ) {
        if ( is_array( $image ) ) { // $image pode ser false em caso de erro
            $novo_src = faceDetector( $image[0] ); // $image[0] é o src
            $image[0] = $novo_src;
        }

        return $image;
    }

ref.: https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.