I rewrote the text of the code for you, there are only a few things I have to tell you.
1 You should put the words you want to search in the $string
variable.
2 To solve the problem of finding hello and hell at the same time, I used the preg_match
function and the problem was solved and now it only finds one word.
preg_match("/\b{$url}\b/", $content)
3 I have used WordPress admin_notices
to display the error message, but in order to delete the message after a certain time, I used the set_transient()
function. In this function, you can set your time instead of 10 seconds
.
Well, the original code is here:
function jhnppdraft($post_id, $post)
{
/** Set harmful words in this array */
$string = " hello , hell , pineapple ";
$prohibited_words = explode(",", $string);
$content = $post->post_content;
/** Search for words in the content of the post */
$searched = [];
foreach ($prohibited_words as $url) {
$url = trim($url);
if (preg_match("/\b{$url}\b/", $content)) {
$searched[] = $url;
}
}
/** check if words are found */
if (!empty($searched)) {
/** set post status to draft */
wp_update_post(array(
'ID' => $post_id,
'post_status' => 'draft',
));
/** show error if words are used */
$text = sprintf(
__(
'Your post has been set to draft since it contains the following words: ("%s"). Please remove them and try publishing again.',
'jhnpp'
),
implode('", "', $searched)
);
/** set_transient Set to show general_admin_notice() */
set_transient('jhnpp', $text, 10); // You can set the display time of admin_notices to seconds
}
}
add_action('publish_post', 'jhnppdraft', 10, 2);
Error message display section:
function general_admin_notice()
{
// Display the error text here
$transient = get_transient('jhnpp');
if(!$transient) return;
echo '<div class="notice notice-warning is-dismissible">
<p>' . $transient. ' </p>
</div>';
}
add_action('admin_notices', 'general_admin_notice');
Here you can see that it recognized the word hello
and did not recognize the word hell
.