从自定义 php 插件文件中的按钮点击调用函数

calling a function from button click in custom php plugin file

我创建了一个自定义警报插件,这样每当在 wordpress 中提交评论时,它就会触发插件功能以显示警报,通知用户他们的评论已成功发布。

现在我可以在发表评论后显示警报,但我想要一种方法 remove/close 用户发出警报。我在警报中添加了一个 (x) 按钮,目的是当用户单击它时 - 警报将消失。

这是我的 functions.php 中的内容,在提交评论时会被触发:

add_action('comment_post', 'comment_custom_alert());

这是我的自定义-alert.php:

function close_custom_alert() {
    echo "hello - testing method.";
    // code to hide alert div
}

function comment_custom_alert() {
   ?>
    <div class="custom-alert" id="comment_custom_alert">
        <div class="alert-success">
            <button type="button" onclick="close_custom_alert()" class="close">&times;</a>
            <strong>Success!</strong> Your comment has been posted successfully.
        </div>
    </div>
    <?php
}

但是当我单击按钮时,我在控制台中看到 close_custom_alert 未定义。不确定我可能遗漏了什么或做错了什么。

我也试过:

<button type="button" onclick="<?php close_custom_alert() ?>" class="close">&times;</a>

但在尝试之后我会得到 "Uncaught SyntaxError: Unexpected identifier"

你可以为此使用一些 js:

this.parentNode.parentNode.remove()

将您的 html 更新为:

    <div class="custom-alert" id="comment_custom_alert">
        <div class="alert-success">
            <button type="button" onclick="this.parentNode.parentNode.remove()" class="close">&times;</button>
            <strong>Success!</strong> Your comment has been posted successfully.
        </div>
    </div>