Get Ajax to work for all Users on Wordpress

2019-05-26 04:17发布

some Plugins that use Ajax in Wordpress only work when you are logged in as admin or added these hooks:

add_action('wp_ajax_my_action', 'my_action_callback'); 
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');

But I'm really having a hard time with getting everything to work for non-admin users and I'm wondering if there is a easy way (for js/php noobs) to tell wordpress to globally activate all ajax functions for alls users, wether logged in or not.

I know this is probably a very stupid and risky way if that is possible somehow, but please let me know!?!!?

1条回答
仙女界的扛把子
2楼-- · 2019-05-26 05:09

PHP wise, you've hit the nail on the head with your code above. This is required for each AJAX action, as each action will of course call a different function.

Now, I'm making the assumption that you are using the default Wordpress AJAX call -

jQuery.post(ajax_object.ajax_url, data, function(response) {

If that is indeed the case, for front end calls it is likely that ajax_object.ajax_url is not set. To set this, add the following to your functions.php file -

<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
    <script type="text/javascript">
        var ajax_object = {};
        ajax_object.ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
    </script>
<?php
}
?>
查看更多
登录 后发表回答