I need help generating a custom URL based on the user ID - wordpress

I need help on how generate a unique URL based on a users ID for example
var htmlstring = "https://www.google.com" + "?" + <?php get_userdata( $userid ); ?>
This is the JS I have that creates a hyperlink in the html:
Click <script type="text/javascript">
function zs_open_window(url, height, width){var leftPos = 0;var topPos = 0;if(screen){leftPos = (screen.width - width) / 2;topPos = (screen.height - height) / 2;window.open(url, null, 'width='+width+',height='+height+',left='+leftPos+',top='+topPos+', toolbar=0, location=0, status=1, scrollbars=1, resizable=1');}}</script>HERE
I need to get the Wordpress username as a JS variable so I can modify the href to be href="https://survey.zohopublic.com/zs/NbB3YM?USERNAME".
I know how to modify the href, I just don't know how push a username into a JS variable?
Ben

You could setup a global variable on all pages that holds that information by adding this to your header.php file just above the <?php wp_head(); ?> line.
<?php
// Gets the current user.
$current_user = wp_get_current_user();
// Checks if the visitor is logged in.
if ( $current_user->ID !== 0 ) {
// Output JS
?>
<script type="text/javascript">
var htmlstring = "https://survey.zohopublic.com/zs/NbB3YM?username=<?php echo $current_user->user_login ?>";
</script>
<?php
} // End if
?>
You can then use htmlstring in any of your other JS functions or code. I also added the username= parameter as you might need that so you can pass it to something else. If you don't, just remove it.

Related

How to add a nonce to an inline script in WordPress

I'm trying to add a nonce to the inline scripts inserted in WordPress by wp_add_inline_script and wp_localize_script, but I can't figure out how to do it. It looks there are no WordPress filters for that. My goal is to have a nonce for inline scripts, so I can define a Content Security Policy that would not break common plugins that insert inline scripts. At the end the result should be something that looks like:
<script type="text/javascript" nonce="xxxxxxxxxx">....</script>
where xxxxxxxx is the nonce.
Do you have any ideas?
As the HTML for inline scripts are generated by the WordPress code
sprintf( "<script type='text/javascript'>\n%s\n</script>\n", ... )
you cannot add an attribute to the HTML script element using wp_add_inline_script() as <script type='text/javascript'> is hard coded.
However, the filter 'script_loader_tag' will allow you to change the HTML for script elements just before it is outputted by WordPress.
Note that the filter 'script_loader_tag' will not be applied to script elements added by calling wp_localize_script() since these are outputted by the WordPress code:
echo "<script type='text/javascript'>\n"; // CDATA and type='text/javascript' is not needed for HTML 5
echo "/* <![CDATA[ */\n";
echo "$output\n";
echo "/* ]]> */\n";
echo "</script>\n";
Since these are echoed and <script type='text/javascript'> is hard coded you cannot add an attribute to the HTML script elements of wp_localize_script().
Try to use wp_enqueue_scripts hook
function my_special_inline_script() {
?>
<script>
// your JS code
</script>
<?php
}
add_action( 'wp_enqueue_scripts', 'my_special_inline_script', 1, 1 );
or
function theme_prefix_enqueue_script() {
wp_add_inline_script( 'jquery', 'jQuery(document).ready(function(){});' );
}
add_action( 'wp_enqueue_scripts', 'theme_prefix_enqueue_script' );
Bit late to the party but I just faced this exact problem for the same reasons.
I solved it for wp_add_inline_script by a bit of simple str_replace action.
add_filter( 'script_loader_tag', 'add_nonce_to_script_tag', 10, 3 );
function add_nonce_to_script_tag( $tag, $handle, $src ) {
// Check the $handle and respond accordingly
if ( $handle === 'my-script' ) {
$nonce_value = wp_create_nonce('my__script__nonce'); // or ref to an existing nonce
$replace = sprintf("javascript' nonce='%s'>", $nonce_value );
$tag = str_replace( "javascript'>", $replace, $tag);
}
return $tag;
}
// Then... $data is the inline JS from wherever
wp_add_inline_script('my-script', $data, 'before');
Once the inline script loads, I am seeing the script tag output with a nonce attribute. This is working fine with my Content-Security-Policy.
Check this out
"WordPress 5.7 adds a handful of new functions that enables passing attributes, such as async or nonce"

Get someone elses public instagram feed

Lots of widgets and snippets out there for displaying your own feed but cant seem to find anything for displaying someone else's public feed.
Need this for a project I'm working on.
http://instafeedjs.com claims you can get images based on a tag which would almost suffice but it doesn't work so I assume the Instagram API has since been refined.
Why would Instagram restrict access to what is available publicly?
Instagram looks like they did restrict their API but you can still get user info when a request is made with the url below:
https://www.instagram.com/{username}/?__a=1
E.g: This url will get all information about a user who's username is therock
https://www.instagram.com/therock/?__a=1
This was my solution, specifically this applies to wordpress:
<?php
// The instagram user eg: elonmusk
$instagramId = get_field('instagram_id');
if($instagramId) {
$request = wp_remote_get( 'https://www.instagram.com/' . $instagramId . '/?__a=1' );
if( is_wp_error( $request ) ) { return false; // Something }
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body, true );
// Get the actual user ID eg: 3602415960
$userID = $data["user"]["id"];
}?>
And then finally use the userID in instafeedjs to display the feed.
<div id="instafeed">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/instafeed.js/1.4.1/instafeed.min.js"></script>
<script type="text/javascript">
var php_var = "<?php echo $userID; ?>";
var userFeed = new Instafeed({
get: 'user',
userId: php_var,
clientId: '*******Enter yours******',
accessToken: '4622774.7cbaeb5.ec8c5041b92b44ada03e4a4a9153bc54',
template: '<img src="{{image}}" style="width:25%;"/>',
sortBy: 'most-recent',
limit: 24,
links: false
});
userFeed.run();
</script>
http://instafeedjs.com
https://pippinsplugins.com/using-wp_remote_get-to-parse-json-from-remote-apis/
I really hope this helps someone else.

get_field() of ACF plugin wordpress assign to javascript value

Im having a problem of assigning data of get_field() to a javascript variable
<?php $event_message = get_field('event_message');?>
<script>
var event_message = '<?php echo $event_message; ?>';
console.log(event_message);
</script>
it gave me empty value. Am I missing something?
Your code looks fine. However, be sure to be inside the Wordpress loop or else you would have to pass the $post_id parameter to your get_field() call, like this :
<?php $event_message = get_field('event_message', $post_id); ?>
If that doesn't do the trick, we're gonna need more code to find what's wrong !
You can probably just assign the Javascript variable directly from the ACF field. So try changing your code to:
<script>
var event_message = '<?php the_field("event_message"); ?>';
console.log(event_message);
</script>
That should work, hopefully!

It is possible to add php to this script in Wordpress?

I use this script to filter posts from single category. I based on tags which generate also a class. It is possible to generate this script by WordPress with all tags from my site?
For example below 2 scripts (now I have 12 scripts of this type):
$(document).ready(function(){
$('tr').show();
$("#aipa").click(function(){
$("tr").show();
$('tr:not(:first)').not(".aipa").slideToggle('fast');
});
});
$(document).ready(function(){
$('tr').show();
$("#ris").click(function(){
$("tr").show();
$('tr:not(:first)').not(".ris").slideToggle('fast');
});
});
Now when I add new tags I must manually add another script:
$(document).ready(function(){
$('tr').show();
$("#next-tag").click(function(){
$("tr").show();
$('tr:not(:first)').not("#next-tag").slideToggle('fast');
});
});
Here's a way to do this. This assumes that you're using the standard blog tag system, and that your variable you're using as your ID and class is the tag's slug. Alter it as needed for your needs.
<?php $tags = get_tags(); ?>
<script>
$(document).ready(function(){
<?php foreach ( $tags as $tag ) { ?>
$('tr').show();
$("#<?php echo $tag->slug; ?>").click(function(){
$("tr").show();
$('tr:not(:first)').not(".<?php echo $tag->slug; ?>").slideToggle('fast');
});
<?php } ?>
});
</script>
This will create a single document ready function, and then generate multiple click functions.

Wordpress: Make plugin option to modify jquery

I am trying to add plugin option to update jquery but don't have any idea how to do that. I am adding jquery using wp_enqueue_script() and so it is not allowing to add php function ( get_option() ) to the jquery code. Please help me to resolve this.
Jquery code:
jQuery(document).ready(function(){
$cnt = 0;
jQuery('#add-photo-button').click(function(){
if($cnt == 3){ // where 3 should replaced with plugin option function/varible
jQuery('#add-photo-button').prop('disabled', true);
jQuery('#add-photo-button').addClass('disabled');
}
$cnt++;
var current_count = jQuery('input[type="file"]').length;
//var next_count = current_count + 1;
jQuery('#file-upload').prepend('<p><input type="file" name="photo[]" /></p>');
});
});
Please see the wp_localize_script() function.
You must enqueue your script, then localize (or rather: pass the data as inline JavaScript) the data you want to reference in the JavaScript and lastly update your script to reference the newly localized global object. Please see my example below.
Example
1- Enqueue your script in your plugin, then "localize" the variable data using wp_localize_script(). Make sure you use the same handle for both function calls.
<?php
// !! Edit the variables below to suit your plugin
$add_photo_button_handle = 'some_handle';
$add_photo_button_js = plugins_url( '/add_photo_button.js', __FILE__ );
$photo_num = get_option( 'add_photo_button_cnt' ); // Here you fetch the option data.
// Enqueue your script
wp_enqueue_script( $add_photo_button_handle, $add_photo_button_js );
// Set the data you want to pass to your script here
$data = array( 'photo_button_cnt' => $photo_num );
// Localize the script, the 'photo_button_cnt' value will now be accessible as a property in the global 'add_photo_button' object.
wp_localize_script( $add_photo_button_handle, 'add_photo_button', $data );
?>
2- Change your script to reference the localized object
<script type="text/javascript">
jQuery(document).ready(function(){
$cnt = 0;
jQuery('#add-photo-button').click(function(){
//============================================
// See how we access the localized object.
//============================================
if($cnt == add_photo_button.photo_button_cnt ){
jQuery('#add-photo-button').prop('disabled', true);
jQuery('#add-photo-button').addClass('disabled');
}
$cnt++;
var current_count = jQuery('input[type="file"]').length;
//var next_count = current_count + 1;
jQuery('#file-upload').prepend('<p><input type="file" name="photo[]" /></p>');
});
});
</script>

Resources