tags:

views:

56

answers:

2

Hey all,

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;
}
+1  A: 

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();
    }
}
nickohrn
Sentence. Verb. Noun.
Karl
@Karl - My solution is tested and works. It accomplishes what the OP asked for, but I've edited it to satisfy your need for a few sentences.
nickohrn
Awesome! I hope this doesn't come to hurt me later on though.. The problem I had with their api was they were using PHP with javascript. I would like to avoid that at all costs. Is there another way to call it from functions and still avoid mixing javascript and php?
Matt
A: 

sorry, can't delete this answer ....

cs