User ID and username from wp to shiny/R

Variable from PHP to java

First we use php to get some variables from wordpress with the following code added to a wordpress page.

<?php global $current_user;

get_currentuserinfo();

$user_name = $current_user->user_login;

$user_ID = get_current_user_id();

?>

Then we copy to java and display the output.

<script type="text/javascript">

var username = <?php echo json_encode($user_name) ?> ;

var userID = <?php echo json_encode($user_ID) ?> ;

document.write(‘Your username is ‘+username+’ and user id is ‘+userID+’.’);

</script>

The last line writes out the text which will be:

The iframe

We make an iframe with the code:

<script>

document.domain = "predret.org";

var username = parent.username;
var userID = parent.userID;

document.write('Your username is '+username+' and user id is '+userID+'.');

</script>

And load it with:

<script type="text/javascript">

document.domain = "predret.org";

</script>

<iframe id="example1" style="border: none; width: 100%; height: 500px;" src="http://predret.org/shiny/shiny.tests/App-7/test.html" width="300" height="150" frameborder="0"></iframe>

Note that document.domain is needed both in the wordpress page and the iframe because they are on different domains (different ports are enough).

The iframe shows (border added for clarity):

Getting the variable into shiny

get_user_id.js

document.domain = "predret.org";

var userIDVariableName = parent.userID;

var userID = document.getElementById("userID");

userID.value = userIDVariableName;

var usernameVariableName = parent.username;

var username = document.getElementById("username");

username.value = usernameVariableName;

ui.R

library(shiny)

shinyUI( bootstrapPage(

# Hidden input boxes to save the variable to

HTML(' <input type="text" id="userID" name="userID" style="display: none;"> '),

HTML(' <input type="text" id="username" name="username" style="display: none;"> '),

# include the js code

includeScript("../../scripts/get_user_id.js"),

# Show the output

textOutput("view")

))

Remember to change toe path to the script.

server.R

shinyServer(function(input, output, session) {

userID <- reactive({ input$userID })

username <- reactive({ input$username })

output$view <- renderText( paste0( "User ID is: ",userID()," and username is: ",username() ) )

})

Result:

Leave a Reply

Creative Commons License

The data available on this site is licensed under a
Creative Commons Attribution-ShareAlike 4.0 International License.