I want to use countUp.js on my custom theme in Wordpress.
When I add the file with wp_enqueue_script(), I get an error:
Uncaught SyntaxError: Unexpected token 'export'
I've read that it can be fixed setting on the <script> label type="module", but I don't know how to do that, as that option doesn't exist in wp_enqueue_script()...
Anyone can hel me?
One can add attributes to a script by applying filter 'script_loader_tag'.
Use add_filter('script_loader_tag', 'add_type_attribute' , 10, 3); to add the filter.
Define the callback function like the example given on the link above:
function add_type_attribute($tag, $handle, $src) {
// if not your script, do nothing and return original $tag
if ( 'your-script-handle' !== $handle ) {
return $tag;
}
// change the script tag by adding type="module" and return it.
$tag = '<script type="module" src="' . esc_url( $src ) . '"></script>';
return $tag;
}
I want to address a specificity to Paul Naveda's answer.
Yes it works, but with this your basically losing any additional inline scripts.
What I mean is, when using wp_add_inline_script() function, which basically takes what you are giving it, and either add it just before or after the current 's handle:
wp-includes/class.wp-scripts.php:393 (github)
$tag = $translations . $cond_before . $before_handle;
$tag .= sprintf( "<script%s src='%s' id='%s-js'></script>\n", $this->type_attr, $src, esc_attr( $handle ) );
$tag .= $after_handle . $cond_after;
$tag = apply_filters( 'script_loader_tag', $tag, $handle, $src );
So by doing:
$tag = '<script type="module" src="' . esc_url( $src ) . '"></script>';
You loose the before and after tag.
To make sure you're not losing it, either use wp_localize_script() (it's supposed to only be used for translating though)
or add those lines of codes:
function add_type_attribute($tag, $handle, $src) {
if ('your_handle_here' === $handle) {
/** #var WP_Scripts $wp_scripts */
global $wp_scripts;
$before_handle = $wp_scripts->print_inline_script( $handle, 'before', false );
$after_handle = $wp_scripts->print_inline_script( $handle, 'after', false );
if ( $before_handle ) {
$before_handle = sprintf( "<script type='text/javascript' id='%s-js-before'>\n%s\n</script>\n", esc_attr( $handle ), $before_handle );
}
if ( $after_handle ) {
$after_handle = sprintf( "<script type='text/javascript' id='%s-js-after'>\n%s\n</script>\n", esc_attr( $handle ), $after_handle );
}
$tag = $before_handle;
$tag .= sprintf( "<script type='module' src='%s' id='%s-js'></script>\n", $src, esc_attr( $handle ));
$tag .= $after_handle;
}
return $tag;
}
add_filter('script_loader_tag', 'add_type_attribute' , 10, 3);
It keeps the before and after and print it if present
Keep in mind this is still not perfect, because of $translations variable, but this is another approach if you are using wp_add_inline_script()
This is a little more complicated way to go... But I've used the following to add defer, crossorigin etc...
I don't think it's that official yet but from what I've read it's not a bad way to do it (and I've seen this approach in production for several plugins).
So, (adjust your params/variables to suit obviously) script registering (not just enqueue) is required (see https://developer.wordpress.org/reference/functions/wp_script_add_data/):
wp_register_script('countup-js', 'https://cdnjs.cloudflare.com/ajax/libs/countup.js/2.0.0/countUp.min.js', ['jquery'], $js_version, true);
wp_enqueue_script('countup-js');
wp_scripts()->add_data('countup-js', 'type', 'module');
And then your filter (like the top answer here, but I think this outlines how you can set it up to be more reusable, flexible etc)
add_filter('script_loader_tag', 'moduleTypeScripts', 10, 2);
function moduleTypeScripts($tag, $handle)
{
$tyype = wp_scripts()->get_data($handle, 'type');
if ($tyype) {
$tag = str_replace('src', 'type="' . esc_attr($tyype) . '" src', $tag);
}
return $tag;
}
To further add to what #Zeldri said, you don't need to make use of wp_localize_script(), we can keep that function for translations as it was first intended for.
Below is the code you'd need if you don't want to lose code added using wp_add_inline_script()
function make_scripts_modules( $tag, $handle, $src ) {
if ( 'your-script-handle' !== $handle ) {
return $tag;
}
$id = $handle . '-js';
$parts = explode( '</script>', $tag ); // Break up our string
foreach ( $parts as $key => $part ) {
if ( false !== strpos( $part, $src ) ) { // Make sure we're only altering the tag for our module script.
$parts[ $key ] = '<script type="module" src="' . esc_url( $src ) . '" id="' . esc_attr( $id ) . '">';
}
}
$tags = implode( '</script>', $parts ); // Bring everything back together
return $tags;
}
add_filter('script_loader_tag', 'make_scripts_modules' , 10, 3);
This will turn the required script into a module and leave the inline scripts alone.
Inspired by #PaulNaveda, #peter and #zeldri
A small plugin demontrating JS modules support, including localization and inline scripts.
Content of wp-content/plugins/js-module-support-demo/js-module-support-demo.php
<?php
/*
Plugin Name: Javascript Module Support - Demo
Plugin URI: https://froger.me/
Description: Javascript Module Support - Demo
Version: 0.1
Author: Alexandre Froger
Author URI: https://froger.me/
*/
/* ---------------------------------------------------------------
* Below is the main logic - it can be used in plugins or a theme
* --------------------------------------------------------------- */
add_filter( 'script_loader_tag', 'add_type_attribute', 10, 3 );
function add_type_attribute( $tag, $handle, $src ) {
$type = wp_scripts()->get_data( $handle, 'type' );
if ( $type && is_string( $type ) ) {
$tag = str_replace( ' src=', 'type="' . esc_attr( $type ) . '" src=', $tag );
}
return $tag;
}
/* ---------------------------------------------------------------------------------------
* Below is the demo code - it adds the demo scripts (main, module, localization, inline)
* --------------------------------------------------------------------------------------- */
add_action( 'wp_enqueue_scripts', 'demo_scripts', 10, 1 );
function demo_scripts() {
$inline_script = '
console.log(\'this is an inline script added to demo.js\');
';
wp_enqueue_script( 'demo', plugin_dir_url( __FILE__ ) . 'js/demo.js', array(), false, true );
wp_scripts()->add_data( 'demo', 'type', 'module' );
wp_add_inline_script( 'demo', $inline_script );
wp_localize_script( 'demo', 'LocalizationVar', array( 'key' => 'value' ) );
}
Content of wp-content/plugins/js-module-support-demo/js/demo.js
import moduleVar from './module.js'
console.log(moduleVar);
console.log(window.LocalizationVar);
Content of wp-content/plugins/js-module-support-demo/js/module.js
const moduleVar = 'This is a variable from module.js';
export default moduleVar;
Upon execution of the full demo code, the following is seen in the console:
this is an inline script added to demo.js
This is a variable from module.js
{"key":"value"}
we have construct the one secret URL for my application.i have PHP script how to change java script any one help me to solve the issue
Below mentioned script how to change java script in c# application
i have php script this to change javascript
<html>
<title>Live</title>
<head>
<script src="http://content.jwplatform.com/libraries/Y09dkRGs.js"></script>
<script>jwplayer.key = "ti8UU55KNdJCPX+oWrJhLJNjkZYGiX13KS7yhlM7Ok/wmU3R";</script>
</head>
<body>
<?php
function bg_gen_secure_uri($file, $directory, $secret, $expiry=0, $allowed_countries='',
$disallowed_countries='', $allowed_ip='', $allowed_useragent='',
$allowed_metros='', $disallowed_metros='',
$progressive_start='', $progressive_end='',
$extra_params='') {
if ($file==''||$secret=='') {
return false;
}
// Construct the values for the MD5 salt ...
if (substr($expiry,0,1)=='=') {
$timestamp=substr($expiry,1);
} else if ($expiry > 0) {
$now=time(); // use UTC time since the server does
$timestamp=$now+$expiry;
} else {
$timestamp=0;
}
if ($allowed_countries) {
$allowed_countries='&a='.$allowed_countries;
}
if ($disallowed_countries) {
$disallowed_countries='&d='.$disallowed_countries;
}
if ($allowed_ip) {
$allowed_ip='&i='.$allowed_ip;
}
if ($allowed_useragent) {
$allowed_useragent='&u='.$allowed_useragent;
}
if ($progressive_start!='') {
$progressive_start='&start='.$progressive_start;
}
if ($progressive_end) {
$progressive_end='&end='.$progressive_end;
}
if ($allowed_metros) {
$allowed_metros='&am='.$allowed_metros;
}
if ($disallowed_metros) {
$disallowed_metros='&dm='.$disallowed_metros;
}
if ($extra_params) {
$extra_params=urldecode($extra_params);
}
// Generate the MD5 salt ...
if ($directory == '') {
$salt = $secret . $file . '?e=' . $timestamp . $allowed_countries .
$disallowed_countries . $allowed_metros . $disallowed_metros . $allowed_ip .
$allowed_useragent . $progressive_start . $progressive_end;
} else {
$salt = $secret . $directory . '?e=' . $timestamp . $allowed_countries .
$disallowed_countries . $allowed_metros . $disallowed_metros . $allowed_ip .
$allowed_useragent . $progressive_start . $progressive_end;
}
// Generate the MD5 hash ...
$hash_code = md5($salt);
// Generate the link ...
$url = $file . '?e=' . $timestamp . $allowed_countries . $disallowed_countries .
$allowed_metros . $disallowed_metros . $allowed_ip . $allowed_useragent .
$progressive_start . $progressive_end . '&h=' . $hash_code . $extra_params;
return $url;
}
function get_secure_url($file,$directory,$secret) {
$expiry=3600;
$allowed_countries='';
$disallowed_countries='';
$allowed_ip='';
$allowed_useragent='';
$allowed_metros='';
$disallowed_metros='';
$progressive_start='';
$progressive_end='';
$extra_params='&bgsecuredir=1';
return bg_gen_secure_uri($file, $directory, $secret, $expiry, $allowed_countries, $disallowed_countries, $allowed_ip, $allowed_useragent, $allowed_metros, $disallowed_metros, $progressive_start, $progressive_end, $extra_params);
}
$url = 'http://tv.live-s.cdn.bitgravity.com/cdn-live/_definst_/tv'.get_secure_url('/secure/live/tv/playlist.m3u8','/tv/secure/','kkkfdashfsdiads');
?>
<div>
<div id="player">
<div id="myElement"> </div>
<script type="text/javascript">
jwplayer("myElement").setup({
file: '<?=$url?>',
width: '100%',
aspectratio: '16:9',
stretching:'exactfit',
autostart: false,
androidhls: true,
skin: 'vapor',
primary: 'html5'
});
</script>
</div>
</div>
Install Composer from http://getcomposer.org/
Add the "base-reality/php-to-javascript": ">=0.0.3" to your project's
composer.json file:
"require":{ "base-reality/php-to-javascript": "0.1.16" }
Or the latest tagged version. The dev master should only be used for
development, not production.\
Include the Composer SPL autoload file in your project:
require_once('../vendor/autoload.php');
Call the converter:
$phpToJavascript = new PHPToJavascript\PHPToJavascript();
$phpToJavascript->addFromFile($inputFilename); $jsOutput =
$phpToJavascript->toJavascript();
$jsOutput will now contain an auto-generated Javascript version of
the PHP source file.
Hope this helps!
Thanks
You can convert PHP syntax to JS with https://gitlab.com/kornelski/babel-preset-php
I'm trying to use the dropzone JS plugin, and PHP to upload multiple files and then output each file url.
I have this so far:
$upload_dir = 'files';
for($i=0; $i<count($_FILES['file']['tmp_name']); $i++) {
$tempFile = $_FILES['file']['tmp_name'][$i];
$uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR;
$mainFile = $uploadPath.time().'-'. $_FILES['file']['name'][$i];
$mainFile_short = time().'-'. $_FILES['file']['name'][$i];
if(move_uploaded_file($tempFile,$mainFile)) {
}
}
I can't seem to make this work though, I'm not sure where I'm going wrong. Any ideas would be great!
$img = $_FILES['file'];
$upload_dir = 'files';
if(!empty($img))
{
$img_desc = reArrayFiles($img);
print_r($img_desc);
foreach($img_desc as $val)
{
$tempFile = $val['tmp_name'];
$uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR;
$mainFile = $uploadPath.time().'-'. $val['name'];
$mainFile_short = time().'-'. $val['name'];
if(move_uploaded_file($tempFile,$mainFile)) {
}
}
}
I am trying to install Magento community edition 1.9.2.1 into cPanel through Godaddy. I have so far extracted the tar file into the file manager, moved all the items in the Magento folder into root, and given folders proper permissions to run.
When I go into my website to open up the installation wizard I see this
I cannot click the continue button it doesn't work. When I inspect the page I get these errors.
I think its a jQuery problem. Looks like the website doesn't load any JavaScript. I tried adding a jQuery CDN link to the head but no avail. I have saved a jQuery CDN into my file system and called it through head still nothing.
I don't know what's the problem. JavaScript is enabled in my browser, so it should work.
i think this should be permission issue.i have attached a code,copy that in a new file(eg. magento-cleanup.php ) and upload to your magento root and run it using url(http://youdomain/magento-cleanup.php). it helps you to fix permission issue.
<?php
## Function to set file permissions to 0644 and folder permissions to 0755
function AllDirChmod( $dir = "./", $dirModes = 0755, $fileModes = 0644 ){
$d = new RecursiveDirectoryIterator( $dir );
foreach( new RecursiveIteratorIterator( $d, 1 ) as $path ){
if( $path->isDir() ) chmod( $path, $dirModes );
else if( is_file( $path ) ) chmod( $path, $fileModes );
}
}
## Function to clean out the contents of specified directory
function cleandir($dir) {
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && is_file($dir.'/'.$file)) {
if (unlink($dir.'/'.$file)) { }
else { echo $dir . '/' . $file . ' (file) NOT deleted!<br />'; }
}
else if ($file != '.' && $file != '..' && is_dir($dir.'/'.$file)) {
cleandir($dir.'/'.$file);
if (rmdir($dir.'/'.$file)) { }
else { echo $dir . '/' . $file . ' (directory) NOT deleted!<br />'; }
}
}
closedir($handle);
}
}
function isDirEmpty($dir){
return (($files = #scandir($dir)) && count($files) <= 2);
}
echo "----------------------- CLEANUP START -------------------------<br/>";
$start = (float) array_sum(explode(' ',microtime()));
echo "<br/>*************** SETTING PERMISSIONS ***************<br/>";
echo "Setting all folder permissions to 755<br/>";
echo "Setting all file permissions to 644<br/>";
AllDirChmod( "." );
echo "Setting pear permissions to 550<br/>";
chmod("pear", 550);
echo "<br/>****************** CLEARING CACHE ******************<br/>";
if (file_exists("var/cache")) {
echo "Clearing var/cache<br/>";
cleandir("var/cache");
}
if (file_exists("var/session")) {
echo "Clearing var/session<br/>";
cleandir("var/session");
}
if (file_exists("var/minifycache")) {
echo "Clearing var/minifycache<br/>";
cleandir("var/minifycache");
}
if (file_exists("downloader/pearlib/cache")) {
echo "Clearing downloader/pearlib/cache<br/>";
cleandir("downloader/pearlib/cache");
}
if (file_exists("downloader/pearlib/download")) {
echo "Clearing downloader/pearlib/download<br/>";
cleandir("downloader/pearlib/download");
}
if (file_exists("downloader/pearlib/pear.ini")) {
echo "Removing downloader/pearlib/pear.ini<br/>";
unlink ("downloader/pearlib/pear.ini");
}
echo "<br/>************** CHECKING FOR EXTENSIONS ***********<br/>";
If (!isDirEmpty("app/code/local/")) {
echo "-= WARNING =- Overrides or extensions exist in the app/code/local folder<br/>";
}
If (!isDirEmpty("app/code/community/")) {
echo "-= WARNING =- Overrides or extensions exist in the app/code/community folder<br/>";
}
$end = (float) array_sum(explode(' ',microtime()));
echo "<br/>------------------- CLEANUP COMPLETED in:". sprintf("%.4f", ($end-$start))." seconds ------------------<br/>";
?>
I want to rename a file uploaded with dropzone.js. I have read the other question of rename file with dropzone, but I don't understand.
I've tried this:
this.on("sending", function(file, xhr, formData) {
var abdocument.getElementById("a").value
var nick = document.getElementById("b").value;
formData.append("fileName", a+ " - " + b);
});
}
};
but then how can I use this "fileName"? I've to use in php function? This is mine:
<?php
$upload_folder = 'uploads';
if (!empty($_FILES)) {
$temp_file = $_FILES['file']['tmp_name'];
$target_path = dirname( __FILE__ ) . '/' . $upload_folder . '/';
$target_file = $target_path . $_FILES['file']['name'];
if( file_exists( $target_path ) ) {
move_uploaded_file($temp_file, $target_file);
} else {
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
}
}
?>
or can I rename via javascript?
Thanks to all
Ok, I have to do this:
$_FILES['file']['name'] = ($_POST["fileName"]);
simply set it at $_FILE superglobal as follow:
$_FILES['file']['name']="your_new_file_name";