Support

Account

Home Forums Backend Issues (wp-admin) Set a custom field as featured image caption

Solving

Set a custom field as featured image caption

  • I would like to set the contents of a custom field called featured_image_author as the caption for that post’s featured image. Is that possible?

  • You need to create an acf/save_post filter and update the image post with it

    
    add_filter('acf/save_post', 'update_featured_image_caption', 20, 1);
    function update_featured_image_caption($post_id) {
      // get the featured image id of the post
      $id = get_post_thumbnail_id();
      // if not set, exit
      if (!$id) {
        return;
      }
      // get the field you want to use for the image captions
      $excerpt = get_field('your-field-name', $post_id);
      // if not set, exit
      if (!$excerpt) {
        return;
      }
      // get the attachment post
      $attachment = get_psot($id);
      // alter the caption (post_excerpt)
      $attachment->post_excerpt = $excerpt;
      // disable this filter to prevent infinite loop
      remove_filter('acf/save_post', 'update_featured_image_caption', 20);
      // update the attachment post
      wp_update_post($attachment);
      // re-enable this filter
      add_filter('acf/save_post', 'update_featured_image_caption', 20, 1);
    }
    
  • It caused a critical error when I updated a post.

  • Turn on debugging, there might be an error in my code since I typed it here https://codex.wordpress.org/WP_DEBUG

  • Support pointed out that there is a typo, but this worked perfectly for me. Fixed typo below:

    add_filter('acf/save_post', 'update_featured_image_caption', 20, 1);
    function update_featured_image_caption($post_id) {
      // get the featured image id of the post
      $id = get_post_thumbnail_id();
      // if not set, exit
      if (!$id) {
        return;
      }
      // get the field you want to use for the image captions
      $excerpt = get_field('your-field-name', $post_id);
      // if not set, exit
      if (!$excerpt) {
        return;
      }
      // get the attachment post
      $attachment = get_post($id);
      // alter the caption (post_excerpt)
      $attachment->post_excerpt = $excerpt;
      // disable this filter to prevent infinite loop
      remove_filter('acf/save_post', 'update_featured_image_caption', 20);
      // update the attachment post
      wp_update_post($attachment);
      // re-enable this filter
      add_filter('acf/save_post', 'update_featured_image_caption', 20, 1);
    }
Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Set a custom field as featured image caption’ is closed to new replies.