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 });
});
}
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 });
});
}
Share
Improve this question
asked Apr 30, 2014 at 23:13
js111js111
1,3144 gold badges30 silver badges59 bronze badges
3
- Do you know how to get the user id first? – Ali Gajani 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 – js111 Commented Apr 30, 2014 at 23:24
- Yeah just put that in. – Ali Gajani Commented Apr 30, 2014 at 23:51
3 Answers
Reset to default 3Put 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.
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.
You probably want to use wp_localize_script
. Here is a good explanation of it:
https://wordpress.stackexchange./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.