doubingjian2006 2013-01-06 18:55
浏览 55
已采纳

在wordpress中创建ajax调用。 我需要包括什么才能访问wordpress功能

I am performing an jquery ajax request inside my wordpress. This calls an internal php script. This php script needs to be able to access certain wordpress features like... functions.php which is simple for me to include. What i cant do is access info like the current wordpress user, the $wpdb object. My question is... is there some wordpress file which i can include which gives me access to all that data (and functions.php). I hope you understand what i am accessing as i am aware that was probably THE crappest explaination in the world :D

  • 写回答

4条回答 默认 最新

  • dsf487787 2013-01-06 19:01
    关注

    THE BAD WAY (as pointed out by others)

    When I created some custom PHP to use with wordpress I included the wp-load.php file. Which then loads everything required, including $wpdb.

    require_once('wp-load.php'); // relative path from your PHP file
    
    global $wpdb;
    $wpdb->show_errors = TRUE; // useful for when you first start
    

    I found it was a decent starting point for a quick fix. However you have to remember this will load in a lot more functionality than you may actually require. Thus resulting in slower performance times.

    THE GOOD WAY

    Once functionality became more complex the 'bad' implementation wasn't proving to be all that great. So I moved onto writing plugins instead. The WordPress codex contains good information on working with AJAX and plugins: http://codex.wordpress.org/AJAX_in_Plugins

    In the most basic form you will need to register your AJAX hook:

    // 'wp_ajax_foo' is the hook, 'foo' is the function that handles the request
    add_action( 'wp_ajax_foo', 'foo');
    

    You will also need the corresponding function (in this case foo):

    function foo() {
        // handle the AJAX request
        $bar = $_POST['bar'];
    }
    

    Then in your JavaScript you identify which hook to use with the action attribute but leave out the wp_ajax part:

    $.post(ajaxurl, { action: 'foo', bar: true }, function(response) {
        // do something with response
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?