Last active
September 29, 2021 09:33
-
-
Save vivianspencer/bf4d24de06a4b90cf25e8e7474cf27d8 to your computer and use it in GitHub Desktop.
Require featured Images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Require Featured Images | |
* | |
* @param $post_id | |
*/ | |
function check_thumbnail($post_id) | |
{ | |
$post_status = get_post_status($post_id); | |
if ('trash' !== $post_status && 'auto-draft' !== $post_status) { | |
// change to any custom post type | |
$post_type = get_post_type($post_id); | |
if (!in_array($post_type, ['post'])) { | |
return; | |
} | |
if (!has_post_thumbnail($post_id)) { | |
// set a transient to show the users an admin message | |
set_transient('has_post_thumbnail', 'no'); | |
// unhook this function so it doesn't loop infinitely | |
remove_action('save_post', __NAMESPACE__ . '\\check_thumbnail'); | |
// update the post set it to draft | |
wp_update_post(['ID' => $post_id, 'post_status' => 'draft']); | |
add_action('save_post', __NAMESPACE__ . '\\check_thumbnail'); | |
} else { | |
delete_transient('has_post_thumbnail'); | |
} | |
} | |
} | |
add_action('save_post', __NAMESPACE__ . '\\check_thumbnail'); | |
/** | |
* Check if the transient is set, and display the error message | |
*/ | |
function check_thumbnail_error() | |
{ | |
if (get_transient('has_post_thumbnail') == 'no') { | |
echo '<div class="error notice notice-error is-dismissible"><p>'. __('You must select Featured Image. Your Post is saved but it can not be published.') .'</p></div>'; | |
delete_transient('has_post_thumbnail'); | |
} | |
} | |
add_action('admin_notices', __NAMESPACE__ . '\\check_thumbnail_error'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment