Support

Account

Home Forums Front-end Issues Set image as featured image – ACF Image Crop Add-on

Solved

Set image as featured image – ACF Image Crop Add-on

  • Hello!

    This topic is an example of code that sets the thumbnail post via image field:

    <?php
     
    function acf_set_featured_image( $value, $post_id, $field  ){
        
        if($value != ''){
    	    //Add the value which is the image ID to the _thumbnail_id meta data for the current post
    	    add_post_meta($post_id, '_thumbnail_id', $value);
        }
     
        return $value;
    }
    
    // acf/update_value/name={$field_name} - filter for a specific field based on it's name
    add_filter('acf/update_value/name=cursusfoto', 'acf_set_featured_image', 10, 3);
     
    ?>

    I use the plugin Advanced Custom Fields: Image Crop Add-on. As the image field, it returns the ID of the image. But for some reason this code does not work with the field created by this plugin. Anybody can modify the code? Many thanks.

  • Hi @buylov

    Could you please check what is the returned value for the cropped image? You can use var_dump() to check it up. This page should give you more idea about it: http://www.advancedcustomfields.com/resources/debug/.

    Thanks!

  • I checked it out. For example.

    If the image is not cropped:

    string(3) "929"

    If the image has been cropped:

    int(991)

  • Hi @buylov

    It’s possible that you can’t use that hook with this addon. Could you please ask the plugin author if this is possible?

    Thanks!

  • Author plugin answered in this topic.

    This code works.

    function acf_set_featured_image( $value, $post_id, $field  ){
      $id = $value;
      if( ! is_numeric( $id ) ){
        $data = json_decode( stripcslashes($id), true );
        $id = $data['cropped_image'];
      }
      update_post_meta( $post_id, '_thumbnail_id', $id );
      return $value;
    }
    
    // acf/update_value/name={$field_name} - filter for a specific field based on it's name
    add_filter( 'acf/update_value/name=fieldname', 'acf_set_featured_image', 10, 3 );
  • I know this is an old topic, but after doing this for some time I’ve just recently realized that using a filter isn’t needed. All you really need to do is create an image field with the field name of “_thumbnail_id”, and ACF will just update the featured image for you. There’s no error checking, but simply making your image field required deals what that problem.

    Just thought I add this for anyone that finds this topic.

Viewing 6 posts - 1 through 6 (of 6 total)

The topic ‘Set image as featured image – ACF Image Crop Add-on’ is closed to new replies.