• I have looked at a number of AJAX-related articles on the web and on codex.www.ads-software.com and developer.www.ads-software.com, including https://codex.www.ads-software.com/AJAX_in_Plugins, but I have not found an answer to this question.

    I am developing a custom plugin that enqueues a javascript/jQuery script on the front side which makes a call to admin-ajax.php to retrieve a custom DIV from wp_ajax_my_action (my_action_callback) which has been hooked with add_action.

    I want the content of the DIV to be based on various $post and postmeta information. But, even though I have included “global $post;” in the action callback function, $post is empty.

    When displaying a page, which is when the front-side script is loaded, it would seem to me that this would be in “The Loop” and $post should be available simply needing to be referenced as a global in the function.

    Is this not so?

    The only method I have determined of having access to the post info is by including the post ID in the data (array) argument to wp_localize_script() when enqueuing the front-side script.

    Is this the proper way to get access to $post info? Or is there a better way to access the post information in an admin ajax action callback?

    Edit: P.S. Both ‘get_the_ID()’ and ‘is_page()’ also do not work in the action callback function.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The global $post variable is only available inside the Loop – so, once your page is completely rendered and handed off to the browser as HTML, it no longer exists.

    You’ll need to pass a post ID in your AJAX call so that the server knows which post to retrieve. One the server side, you’ll need to retrieve the post based on the ID Passed through the AJAX call, and then do whatever you need to do with it.

    You can get the Post ID from an element in the HTML as long as you put it there while the page is being rendered on the server side.

    Thread Starter Gone Fishin

    (@terryg-1)

    once your page is completely rendered and handed off to the browser as HTML, [the global $post variable] no longer exists.

    Ah. That explains it.

    Thank you.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘$post info not available in admin-ajax action callback?’ is closed to new replies.