Skip to content

Instantly share code, notes, and snippets.

@mrkdevelopment
Last active September 30, 2021 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrkdevelopment/9bbc2950fe57cd9a675d33684f964a71 to your computer and use it in GitHub Desktop.
Save mrkdevelopment/9bbc2950fe57cd9a675d33684f964a71 to your computer and use it in GitHub Desktop.
How to save a thumbnail ID and make sure the attached Post ID is referenced in Media Library
<?php
add_action('save_post', 'relate_post_to_thumb');
function relate_post_to_thumb($post_id) {
//does this post have a URL / thumbnail
$thumb_id = get_post_thumbnail_id($post_id);
//if thumb found relate to post
if($thumb_id){
//does our thumb have a post parent
if(!has_post_parent($thumb_id)){
wp_update_post(
array(
'ID' => $thumb_id,
'post_parent' => $post_id
)
);
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment