Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass user ID in Javascript function in wordpress?

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 });
});
}
like image 538
js111 Avatar asked Apr 30 '14 23:04

js111


2 Answers

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.

like image 117
NotoriousWebmaster Avatar answered Nov 15 '22 00:11

NotoriousWebmaster


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.

like image 28
Victory Avatar answered Nov 15 '22 00:11

Victory