0

For a theme I'm building I'm looking to dynamically load in a selection of posts with Ajax depending on if a user selects a category or a year ('show all posts in 2012').

I've seen many different approaches described on how to implement Ajax in WordPress but they all do one aspect (like infinite scroll for instance). I was wonder if there is one integrated solution that allows to give a variable to the loop via Ajax and a specific selection of posts is returned?

1

You can easily add whatever variables you want to your AJAX call.

Using jQuery you can set a AJAX action like this:

jQuery.post(
    'your-url-to-admin-ajax.php',
    {
        action: 'your_called_function',
        argument: 'year' or 'category',
        some_other_var: 'some value'
    },
    function( response ) {
        if(response) {
        } else {
        }
    }
);

Then in your functions.php add this:

add_action( 'wp_ajax_nopriv_your_called_function', 'your_called_function' );
add_action( 'wp_ajax_your_called_function', 'your_called_function' );
function your_called_function() {
    $argument = $_POST['argument'];
    $otherVar = $_POST['some_other_var'];
    // now you can do the loop with your argument

    // important to add exit(), or it won't work
    exit();
}

In detail here: http://www.makeuseof.com/tag/tutorial-ajax-wordpress/

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.