You can achive this by doing a redirect and passing along query arguments with the filter redirect_post_location
. There is also redirect_term_location
which will work for taxonomies/terms.
First add the admin_notices
action which will always be active, but will only show the notice under certain conditions.
add_action( 'admin_notices', 'general_admin_notice' );
function general_admin_notice(){
global $pagenow;
if ( 'post.php' === $pagenow && isset($_GET['post']) && 'custom_post_type' === get_post_type( $_GET['post'] ) ){
if ( isset($_GET['empty'])) {
// Turn string into array, so we can loop trough it.
$terms_id = explode( ',', $_GET['empty'] );
echo '<div class="notice notice-error is-dismissible">
<p>';
foreach ( $terms_id as $term_id ) {
$term = get_term( $term_id, 'custom_taxonomy' );
echo '<a href="'.get_term_link( $term ).'">'.$term->name.'</a>, ';
}
echo 'nutrients are empty.</p>
</div>';
}
}
}
Then you need to redirect the page after save and pass a query argument with add_query_arg
. The way I have done it here you can have a dynamic input which is shown in the admin notice.
if ( !empty($empty_error) ) {
add_filter('redirect_post_location', function($loc) use ($empty_error) {
trigger_error( $empty_error);
return add_query_arg( 'empty', implode(',', $empty_error), $loc );
});
}
In my case I do an array_push
on the variable $empty_error
with a term id. The admin notice will then show all the terms which has an error with an link to the respective term.
You can also use removable_query_args
to remove the added query args, so the url looks cleaner. The admin notice will then go away if you reload the page.
add_filter('removable_query_args', 'add_removable_arg');
function add_removable_arg($args) {
array_push($args, 'empty');
return $args;
}