Skip to content

Instantly share code, notes, and snippets.

@Luc45
Created December 27, 2018 19:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Luc45/09f2f9d0c0e574c0285051b288a0f935 to your computer and use it in GitHub Desktop.
Save Luc45/09f2f9d0c0e574c0285051b288a0f935 to your computer and use it in GitHub Desktop.
<?php
/**
* Performs custom validation on custom post type "Site"
*/
function custom_post_site_save($post_id, $post_data) {
# If this is just a revision, don't do anything.
if (wp_is_post_revision($post_id))
return;
if ($post_data['post_type'] == 'site') {
# In this example, we will deny post titles with less than 5 characters
if (strlen($post_data['post_title'] < 5)) {
# Add a notification
update_option('my_notifications', json_encode(array('error', 'Post title can\'t be less than 5 characters.')));
# And redirect
header('Location: '.get_edit_post_link($post_id, 'redirect'));
exit;
}
}
}
add_action( 'pre_post_update', 'custom_post_site_save', 10, 2);
/**
* Shows custom notifications on wordpress admin panel
*/
function my_notification() {
$notifications = get_option('my_notifications');
if (!empty($notifications)) {
$notifications = json_decode($notifications);
#notifications[0] = (string) Type of notification: error, updated or update-nag
#notifications[1] = (string) Message
#notifications[2] = (boolean) is_dismissible?
switch ($notifications[0]) {
case 'error': # red
case 'updated': # green
case 'update-nag': # ?
$class = $notifications[0];
break;
default:
# Defaults to error just in case
$class = 'error';
break;
}
$is_dismissable = '';
if (isset($notifications[2]) && $notifications[2] == true)
$is_dismissable = 'is_dismissable';
echo '<div class="'.$class.' notice '.$is_dismissable.'">';
echo '<p>'.$notifications[1].'</p>';
echo '</div>';
# Let's reset the notification
update_option('my_notifications', false);
}
}
add_action( 'admin_notices', 'my_notification' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment