Showing WP_Error message with admin_notice action hook

You can use function add_settings_error.

More details can be found in the WordPress documentation. I have edited your previous answer to include that:

function wpse_189722_limit_tag_words( $term, $taxonomy ) {
    if ($taxonomy === 'post_tag') {
        if ( count( preg_split( '/\s+/', trim( $term ) ) ) > 2 ) {
            add_settings_error('term_too_many_words', 'term_too_many_words', 'Maximum of 2 words allowed, but entered: '. trim($term), 'error');
            // shorten the term to the allowed number of tags
            $normalized_term = $foo = implode(' ', array_slice(preg_split('/\s+/', trim($term)), 0, 2));
            return $normalized_term;
        }
    }

    return $term;
}

add_filter( 'pre_insert_term', 'wpse_189722_limit_tag_words', 10, 2 );

You can also check a nice guide to WordPress notifications here.

Leave a Comment