Support

Account

Home Forums Backend Issues (wp-admin) Get featured image and save as field

Solved

Get featured image and save as field

  • Hi!
    I want to get the featured image of post and save it as a image field. I saw old comments taking about how do it upside down “field to feature”, but no “feature to field”.Anyone know how do it?

    This is the code I saw:

    <?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);
     
    ?>
  • 
    add_action('acf/save_post', 'move_image_to_post_thumbnail');
    function move_image_to_post_thumbnail($post_id) {
      if (get_field('your-image-field-name', $post_id, false)) {
        // get unformatted value
        // we did it above too, no point formatting the value for this
        $image_id = get_field('your-image-field-name', $post_id, false);
        update_post_meta($post_id, '_thumbnail_id', $image_id);
      }
    }
    
  • Yeah!! Works perfectly. Thanks a lot John.

  • Would it be possible to use the same code with some modifications to get the value of a field and use it as the meta-key _yoast_wpseo_focuskw? Something like this:

    add_action('acf/save_post', 'automatic_keywords');
    function automatic_yoast_keywords($post_id) {
      if (get_field('_yoast_wpseo_focuskw', $post_id, false)) {
        // get unformatted value
        // we did it above too, no point formatting the value for this
        $image_id = get_field('_yoast_wpseo_focuskw', $post_id, false);
        update_post_meta($post_id, 'name', $meta);
      }
    }
  • Sorry John, but the code not working 🙁

  • It works inverting the terms 🙂

    add_action('acf/save_post', 'move_image_to_post_thumbnail');
    function move_image_to_post_thumbnail($post_id) {
      if (get_field('_thumbnail_id', $post_id, false)) {
        // get unformatted value
        // we did it above too, no point formatting the value for this
        $image_id = get_field('_thumbnail_id', $post_id, false);
        update_post_meta($post_id, 'image', $image_id);
      }
    }
Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.