I'm interested in loading parts of the interface of our theme over AJAX and wrote a function to handle generic functions. (Code below.)

It works fine, but wp_nav_menu(), when run through this function, doesn't reliably mark links with appropriate classes like "current-menu-item". It works maybe half of the time.

Do you know why this would be? Do any functions / global variables need to be handled that query_posts() won't take care of?

add_action( 'wp_ajax_nopriv_ananda_ajax', 'ananda_ajax_output' );
add_action( 'wp_ajax_ananda_ajax', 'ananda_ajax_output' );

function ananda_ajax_output() {

global $post;

$function   = $_POST['function'];
$parameters = $_POST['parameters'];
$post_id    = $_POST['post_id'];

if ( $post_id && ananda_ajax_is_approved_function( $function ) ) {

    // Query
    query_posts( array( 'p' => $post_id, 'post_type' => 'any' ) );

    // Output the HTML
    ob_start();

    if ( have_posts() ) {

            the_post();

            if ( $parameters ) {
                call_user_func_array( $function, $parameters );
            } else {
                call_user_func( $function );
            }

    } else {
        // No posts
    }

    // Restore original post data. Probably not needed, but standard best practice.
    wp_reset_postdata();

    // Send the output
    $output = ob_get_clean();
    echo $output;

}

wp_die(); // Standard AJAX callback procedure

}

The issue turned out to be elsewhere. But I did learn that there is no way to overwrite the queried URL directly, as it comes from $_SERVER variables.

The answer here had some code for anyone who wants to do that: https://stackoverflow.com/questions/10739721/wordpress-ajax-parse-url

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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