js111
js111

Reputation: 1314

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 });
});
}

Upvotes: 5

Views: 9588

Answers (3)

NotoriousWebmaster
NotoriousWebmaster

Reputation: 3568

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.

Upvotes: 3

melchoir55
melchoir55

Reputation: 7276

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.

Upvotes: 1

Victory
Victory

Reputation: 5890

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.

Upvotes: 2

Related Questions