5

I'm trying to get the current users ID and pass it as a variable into a javascript function (see "USER_ID_GOES_HERE"). Whats the best practice for doing so?

here is my function:

function hide_loading() {
Wild.onChartsReady(function() {
  var series = new Wild.Series("Viewed Post", {
    analysisType: "count",
    timeframe: "this_week",
    interval: "daily",
    groupBy: "title",
    filters: [{"property_name":"author","operator":"eq","property_value":'USER_ID_GOES_HERE'}]
  });
  series.draw(document.getElementById("mine"), { lineWidth: 2 });
});
}
3
  • Do you know how to get the user id first? Commented Apr 30, 2014 at 23:16
  • yeah isnt it this: <?php $user_ID = get_current_user_id(); ?> ... im just not sure how to incorporate that into the JS function. @AliGajani Commented Apr 30, 2014 at 23:24
  • Yeah just put that in. Commented Apr 30, 2014 at 23:51

3 Answers 3

3

Put this in a PHP file, such as your theme's functions.php. I prefer to put it in a custom plugin.

function headcheese() { ?>
    <script type=”text/JavaScript”>
        var current_user_id = '<?php echo get_current_user_id(); ?>';
    </script>
<?php
}
add_action('wp_head', 'headcheese');

This puts the current user ID in a JavaScript global variable. So you can then use it in your filters array.

Sign up to request clarification or add additional context in comments.

2 Comments

"text/javaScript" not ` ”text/JavaScript”`
also for anyone using this method make sure to defer ur script as ur code might execute before the above var is defined.
2

Change this line:

filters: [{"property_name":"author","operator":"eq","property_value":'USER_ID_GOES_HERE'}]

to

filters: [{"property_name":"author","operator":"eq","property_value":<?=get_current_user_id() ?>}]

Note: that this isn't secure for some applications, double check the user id server side.

1 Comment

Yeah, this assumes the JS file is either generated by a PHP script, or lives inside a PHP file. If your JS is in a separate .js file, this definitely will not work.
1

You probably want to use wp_localize_script. Here is a good explanation of it: https://wordpress.stackexchange.com/questions/96370/pass-php-variable-to-javascript

I don't want to reiterate everything in that post. Essentially, you will be passing php variables to the javascript via that function. The variables can then be retrieved from a parameters object within the javascript.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.