Skip to content

Instantly share code, notes, and snippets.

@woodwardtw
Last active May 17, 2022 10:58
Show Gist options
  • Save woodwardtw/27a45a45c627e4ea251337b558bf604c to your computer and use it in GitHub Desktop.
Save woodwardtw/27a45a45c627e4ea251337b558bf604c to your computer and use it in GitHub Desktop.
takes a custom field named enclosure that holds a string of data with the first element being the URL of an image and make it a featured image for the post
add_action( 'publish_post', 'fwp_fi_update', 10, 1 );
function fwp_fi_update ($post_id){
if (get_post_meta( $post_id, 'enclosure', true )) {
$messy_data = get_post_meta( $post_id, 'enclosure', true);
$array_data = explode(PHP_EOL, $messy_data);
$img_url = $array_data[0];
$img_id = fwp_fi_add_img($img_url, $post_id);
fwp_fi_set_featured_img($post_id, $img_id);
}
}
function fwp_fi_add_img($img_url, $post_id){
$desc = 'I do not feel like figuring this out right now.';
$attach_id = media_sideload_image($img_url, $post_id, $desc, 'id');
return $attach_id;
}
function fwp_fi_set_featured_img($post_id, $img_id){
set_post_thumbnail( $post_id, $img_id );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment