Trigger action via button

时间:2018-09-16 作者:Carol.Kar

我正在使用wordpress 4.9.8PHP 7.1.8 我在新的帖子屏幕上添加了一个按钮:

enter image description here

我尝试按以下方式触发按钮:

add_action( \'media_buttons\', \'add_my_media_button\', 99 );
function add_my_media_button() {

    $post = $GLOBALS[\'post_ID\'];
    echo "<a href=\'#\' id=\'insert-my-media\' data-post-id=\'{$post}\' class=\'button\'>Own content</a>";

}

add_action( \'wp_ajax_my_action\', \'updateContent\' );
function updateContent() {

    $post_id = intval( $_POST[\'post_id\'] );

    wp_die(); // this is required to terminate immediately and return a proper response
    $post = array(
        \'ID\'           => $post_id,
        \'post_content\' => \'Insert this content\',
    );

    // Update the post into the database
    wp_update_post( $post );
}

add_action( \'admin_footer\', \'my_media_button_script\' );
function my_media_button_script() {

    ?>
    <script>
        jQuery(document).ready(function ($) {
            $(\'#insert-my-media\').click(function () {
                var post_id = $(this).attr(\'data-post-id\');
                var data = {
                    \'action\': \'updateContent\',
                    \'post_id\': post_id
                };
                console.log("test: " + ajaxurl)
                console.log(data)
                // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
                jQuery.post(ajaxurl, data, function (response) {
                    alert(\'Got this from the server: \' + response);
                });
            });
        });
    </script>

    <?php
}
但是,按submit时,我会得到:

enter image description here

任何关于我为什么会出现这个错误的建议。

上述代码部分摘自官方reference.

2 个回复
最合适的回答,由SO网友:Ahadul 整理而成

删除此行

add_action( \'wp_ajax_my_action\', \'updateContent\' );
添加这两行

add_action( \'wp_ajax_nopriv_updateContent\', \'updateContent\' );
add_action( \'wp_ajax_updateContent\', \'updateContent\' );
希望它能解决你的问题

https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)

SO网友:vikas jain

替换此add_action( \'wp_ajax_my_action\', \'updateContent\' );

具有

add_action( \'wp_ajax_updateContent\', \'updateContent\' ); add_action( \'wp_ajax_nopriv_updateContent\', \'updateContent\' );

快乐编码

结束

相关推荐

小部件更改在定制器AJAX错误到许多选项?

只是通过customizer测试前端小部件的更改,我甚至无法更改标题。Ajax回应说{\"success\":false,\"data\":\"widget_setting_too_many_options\"} 还有一个通知http://prntscr.com/kk518f 但任何地方都没有错误。通知来自这里https://github.com/WordPress/WordPress/blob/56c162fbc9867f923862f64f1b4570d885f1ff03/wp-inclu