开发者

Getting wordpress to play nice with AJAX

开发者 https://www.devze.com 2022-12-17 09:51 出处:网络
How do I use WP functions from AJAX calls. I\'ve looked at the documentation for creating plugins that use ajax, but I couldn\'t figure out how to apply that to regular pages and posts.

How do I use WP functions from AJAX calls. I've looked at the documentation for creating plugins that use ajax, but I couldn't figure out how to apply that to regular pages and posts.

Is there an easy way to just load everything without using their API? I have my way I like to do ajax and would rather not use their stuff.

This is a fluff version of my code:

Javascript (jQuery):

$('.action.next_posts').click(function() {
        var last_date = $(this).attr('title');
        //alert();
        $.ajax({
            url: WP_DIR+'functions.php?action=get_next_posts',
            type: 'POST',
            data: {date : last_date},

            success: function(response) {
                alert(response);
            },

            error: function(error) {
                alert("error");
            }
        });

    });

Functions.php (PHP):

// AJAX controller

if(isset($_GET['action'])) {
    require_once('../../../wp-config.php');

    require_once('../../../wp-includes/classes.php');
    require_once('../../../wp-includes/开发者_如何转开发functions.php');

    wp();
    echo 'ok';
    echo bloginfo('name'); // NOT WORKING. TRIED adding actions..
    return;
}


The following solution should work. You are going to go ahead and post directly to the WordPress installation and intercept the request before WordPress does all the querying that it would normally do. There are some caveats to this method, one of which being that some caching methods will interfere with it, but it should work fairly well for your purposes.

Besides, you said you didn't want to use the specified WordPress API, so this should be right up your alley.

JavaScript:

jQuery(document).ready(function($) {
    $('.action.next_posts').click(function(event) {
        event.preventDefault();
        var last_date = $(this).attr('title');
        $.ajax({
            url: '/',
            type: 'post',
            data: {date : last_date, action: 'get_next_posts'},

            success: function(response) {
                alert(response);
            },

            error: function(error) {
                alert("error");
            }
        });

    });
});

functions.php

add_action('parse_request','my_request_parser');
function my_request_parser($wp) {
    if( 'get_next_posts' == $_POST['action'] ) {
        echo 'ok';
        bloginfo('name');
        exit();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号