Forums

get post and use template tags via ajax (4 posts)

  1. ekitel
    Member
    Posted 3 years ago #

    so I want to get post title and things like that loaded via ajax, but neither get_post or any template tags are definied in the plugin that I created to serve the html via ajax

    how can I have access to all these functions in my plugin?

  2. Otto
    Tech Ninja
    Posted 3 years ago #

    Don't call any of your plugin files directly with the AJAX request. Use the additional variable trick instead.

    Basically, you add your own query variable, then act on it when it is received, bypassing WordPress' own output.

    So, to add a query variable:

    add_filter('query_vars', 'add_my_var');
    
    function add_my_var($public_query_vars) {
    	$public_query_vars[] = 'some_unique_identifier';
    	return $public_query_vars;
    }

    Now, you need to check for that identifier and act on it:

    add_action('template_redirect', 'my_var_output');
    
    function my_var_output() {
    	$myvalue=get_query_var('some_unique_identifier');
    	if ($myvalue) {
    		// do whatever output you like here
    		// you can even use $myvalue to see what the request is for
    		exit; // this stops WordPress entirely
    	}
    }

    And there you go. Now you can call the main WordPress URL with ?some_unique_identifier=myvalue and this will redirect to your plugin and let you make any sort of output you like. Override the header with an application/json content type and throw some JSON back at it, and it's perfect for an AJAX request. Also, because you're in the plugin context, you have full access to all of WordPress' functions.

    Keep in mind that "do whatever output you like" also includes including other files in, if you want to keep that bit in a separate file.

    The WP-Microsummary plugin shows off this method quite well.

  3. ekitel
    Member
    Posted 3 years ago #

    I found it was much easier to just add this at the top of the php file that's creating the html to be served by ajax:

    require_once("../../../wp-config.php");

  4. Otto
    Tech Ninja
    Posted 3 years ago #

    Bad idea. For one thing, it won't work everywhere. The wp-config file is not guaranteed to be at that location. Users can move the wp-config file up a directory (added in 2.6) and the wp-content directory can be located anywhere on the entire filesystem (added in 2.5, I think).. You can't be certain of where you are in relation to WordPress.

    While it works on your site, it won't work everywhere. The method I outlined above works better and avoids any issues like those.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.