I am making a WordPress template, mytemp.php in wordpress 3.9. In this I can use wordpress functions. For example, below works perfectly.

    $(document).ready(function() {
        alert(<?php echo get_current_user_id() ?>);

However, this template file calls some ajax scripts too depending on user input. Over there it doesn't work. For example, below statement returns fatal error "call to undefined function get_current_user_id"

    $sql = 'SELECT x,y FROM table WHERE user_id = ' . get_current_user_id();

I am guessing, I need to tell the ajax script to include some wordpress file or some global variable but I am not sure how.

È stato utile?


I solved it. All I needed to do was to have below include statement.

   include '../../../../wp-load.php';

By including this, it started recognizing the function get_current_user_id()

Altri suggerimenti

Try to include wp-load.php file in ajax file, after including this file wordpress functions are working properly in your ajax file or you need to write a plugin like ajax.php, and then use this plugin file for your ajax file.

After that you can access the wp functions.

Hope it'll helps.

Try this. I just answered a question not too long ago with this style of sql syntax using the function get_current_user_id();

$sql = "SELECT x,y FROM table WHERE user_id = %d", get_current_user_id();

Another solution would be to establish a contract between your ajax script and the javascript that posts to it. So, in your calling php script, you could set up some JSON in your header:

  <?php echo "wp-data = {current_user_id: " . get_current_user_id() "}"; ?>

And then put it in your ajax call:

   url: "",
   method: "post",
   data: {
      . . . //your post data
      current_user_id: wp-data.current_user_id;
   .success(function(response) {})
   .fail(function(response) {} )
   .complent(function(response, status) {};

Your receive should expect "current_user_id" to be on the POST (or GET).

This involves more work, but you save yourself from loading the WP framework each time you make an ajax call.

Don't use the php above if you want to set multiple values. Set an object instead and just call json_encode on it:

    wp_object = (object) array('wp-val1' => wp_func1(), 'wp-val2' => wp_func2());
    <?php echo "wp-data =" . json_encode(wp_object) . ";"; ?>

DRY, just pass the wp-data object directly in your ajax:

  url: "",
  method: "post",
  data: { 
     . . . 
     wp-object: wp-data,
   . . . 

So in your calling script, you would eventuall arrive at:

$sql = "SELECT x,y FROM table WHERE user_id = %d", $_POST['current_user_id']

or `$_POST['wp-object']['current_user_id']

(of course you would set the $_POST value in a ternary prior to this right?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top