0

I am trying to scrape an image from a remote url that is added using a text field in Advanced Custom Fields (hardcoded in the example below), but I don't even know if the process I am using is correct. I read multiple sources, but different functions and techniques are used (media_sideload_image, wp_remote_get, etc), so I am a bit confused.

I used multiple sources to create the following code.

The scraper from here (tested on its own for the following example, works just fine): https://www.ostraining.com/blog/coding/extract-image-php/

I used some info on this post: https://stackoverflow.com/questions/31368072/error-in-fetching-image-using-wp-remote-get-function

And the docs: https://codex.wordpress.org/Function_Reference/media_handle_sideload

So here is my code:

function generate_featured() {
    global $post;
    if($update == false) {
        if ( !function_exists('media_handle_upload') ) {
            require_once(ABSPATH . "wp-admin" . '/includes/image.php');
            require_once(ABSPATH . "wp-admin" . '/includes/file.php');
            require_once(ABSPATH . "wp-admin" . '/includes/media.php');
        }

        $url = 'https://www.google.gr';
        $html = file_get_contents($url);
    preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i',$html, $matches );
    $image_url = $url . $matches[1][0];

        $tmp = download_url( $image_url );
        $file_array = array(
        'name'     => $post_id . '_' . $image_url . '_' . basename( $matches[1][0] ),
        'tmp_name' => $tmp
        );

        // Check for download errors
        if ( is_wp_error( $tmp ) ) {
            @unlink( $file_array['tmp_name'] );
            return false;
        }

        $id = media_handle_sideload( $file_array, $post_id );

        // Check for handle sideload errors.
        if ( is_wp_error( $id ) ) {
            @unlink( $file_array['tmp_name'] );
            return false;
        }

        // Set post thumbnail.
        set_post_thumbnail( $post_id, $id );
    }
}
add_action( 'save_post', 'generate_featured', 10, 3 );

The thing is I don't see any files created on the wp-content/uploads directory. I temporarily used the media_sideload_image($file, $post_id, $desc); function and the file gets created properly but cannot then set it as a featured image.

Any help is appreciated!

10
  • 1
    The code worked for me; but I defined the function like this: function generate_featured( $post_id ), then I commented out the global $post;; and finally (although this is not mandatory..), in the $file_array, I set name like this: 'name' => basename( $image_url ),
    – Sally CJ
    Commented Apr 16, 2018 at 11:14
  • let me give it a try and get back to you Commented Apr 16, 2018 at 11:17
  • You are right! Now works, but I am not getting the expected behavior. As soon as I create a new post I see the image already attached as a featured image. I would expect hat this would appear after saving the post - since the ACF field intended to do the scrape is created only after I select a category. Maybe I am using the wrong action hook? Commented Apr 16, 2018 at 11:24
  • ...I mean I would expect this to run only after I git the 'publish' button Commented Apr 16, 2018 at 11:27
  • 1
    @SallyCJ It's is the CDN used from medium.com. However, since multiple sites were supposed to be scraped, and didn't want to risk same errors, or maintaining each site/cdn separately, I took a different direction and decided to just save the fb meta image on each post and load it from its source directly. Also, please make your comment as an answer so I can give you credit for it. Commented Apr 17, 2018 at 6:50

1 Answer 1

3

The code worked for me; but I defined the function like this: function generate_featured( $post_id ), then I commented out the global $post;; and finally (although this is not mandatory..), in the $file_array, I set name like this: 'name' => basename( $image_url ),

So: (Note that I intentionally didn't include the whole code)

function generate_featured( $post_id, $post, $update ) {
    //global $post;
    if($update == false) {
        ...

        $tmp = download_url( $image_url );
        $file_array = array(
        'name'     => basename( $image_url ),
        'tmp_name' => $tmp
        );

        ...

        // Set post thumbnail.
        set_post_thumbnail( $post_id, $id );
    }
}
add_action( 'save_post', 'generate_featured', 10, 3 );

See https://developer.wordpress.org/reference/hooks/save_post/ if you need (further) help with the save_post hook.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.