admin管理员组

文章数量:1429064

I'm trying to write a widget plugin in Wordpress which creates a javascript tag and drops it in the footer of a page. I know I can use wp_enqueue_script to create this, no problem. But I need to pass a parameter from the widget settings to this script tag.

Example:

wp_enqueue_script( 'script-name', '/js/example.js' );

will render a tag that looks something like this:

<script type='text/javascript' src='/js/example.js'></script>

What I want is to create a tag that looks like this:

<script type='text/javascript' data-id='12345' src='/js/example.js'></script>

where 12345 is passed in from the widget settings.

How do I do this?

I'm trying to write a widget plugin in Wordpress which creates a javascript tag and drops it in the footer of a page. I know I can use wp_enqueue_script to create this, no problem. But I need to pass a parameter from the widget settings to this script tag.

Example:

wp_enqueue_script( 'script-name', '/js/example.js' );

will render a tag that looks something like this:

<script type='text/javascript' src='/js/example.js'></script>

What I want is to create a tag that looks like this:

<script type='text/javascript' data-id='12345' src='/js/example.js'></script>

where 12345 is passed in from the widget settings.

How do I do this?

Share Improve this question asked Jan 16, 2016 at 8:36 Joel LegerJoel Leger 3474 silver badges11 bronze badges 3
  • 3 You might be looking for wp_localize_script – Rohil_PHPBeginner Commented Jan 16, 2016 at 8:38
  • 1 Yeap, you cannot change (not in any easy way at least) the output of wp_enqueue_script() but you can add your own parameters with wp_localize_script(): ottopress./2010/… – dingo_d Commented Jan 16, 2016 at 9:22
  • What about any other way to add straight javascript to the footer? – Joel Leger Commented Jan 16, 2016 at 17:15
Add a ment  | 

3 Answers 3

Reset to default 3

I realise this is an older post however, I honestly don't know if the following is an acceptable way to pass params from a plugin to javascript, but I had the same issue and wanted to share at least one approach! glad for feedback too!

For whatever reason, I ended up using two different ways to pass parameters down from the plugin PHP code to JS code.

The first was fairly simple using the wp_localize_script option.

Here is the plugin PHP snippet:

wp_enqueue_script(
    'dynamic-rss-scripts', /* Handle/Name */
    plugin_dir_url( __FILE__ ) . 'assets/js/dynamic-rss.js', /* Path to the plugin/assets folder */
    //array('jquery', 'xml2json', 'json2xml'), /* Script Dependencies */
    array('jquery'), /* Script Dependencies */
    null, /* null is any version, but could be the specific version of jquery if required */
    false /* if true=add to footer, false=add to header */
);


/*
    Pass any server-side vars down to JS.  These will be exposed as
    php_vars.variablename for example
*/
$jsarray = array(
    'exampleparam'               => 'Example Param Value'
);
wp_localize_script( 'dynamic-rss-scripts', 'php_vars', $jsarray ); 

I am using an array since, in my case, I would generally have a few params to pass.

From the above snippet, the actual param values where quite easy to use in Javascript. Note the php_vars reference in the wp_localize_script line in the above PHP.

So, in the Javascript it is very easy to reference those params by doing this:

console.log('Hello to PHP variables', php_vars);

... and in my case with the above PHP snippet, I could now of course reference my exampleparam parameter by:

console.log('Here is my specific param called exampleparam', php_vars.exampleparam);

The second approach I have used is to simply construct data attributes on a DOM element (in my case this was a container DIV).

In my plugin PHP, I extract the plugin/shortcode params:

extract( shortcode_atts (array (

'url' => '',
'feed-type' => 'list', // This could be for Wordpress or Calendar etc.
'rows' => '5',
'cols' => '1',
'include-image' => 'false',
'image-align' => 'left',
'image-size' => '100',
'include-date' => 'true',
'date-format' => 'dd/mm/yyyy'

), $attrs ));

I do some validation etc. but ultimately, I end up just creating the HTML data atrributes like this:

$content = "<div id='dynamic-rss' class='dynamic-rss-container' ";
    $content .= "data-url='" . $attrs['url'] . "' ";
    $content .= "data-feedtype='" . $attrs['feed-type'] . "' ";
    $content .= "data-rows='" . $attrs['rows'] . "' ";
    $content .= "data-cols='" . $attrs['cols'] . "' ";
    $content .= "data-includeimage='" . $attrs['include-image'] . "' ";
    $content .= "data-imagealign='" . $attrs['image-align'] . "' ";
    $content .= "data-imagesize='" . $attrs['image-size'] . "' ";
    $content .= "data-includedate='" . $attrs['include-date'] . "' ";
    $content .= "data-dateformat='" . $attrs['date-format'] . "'";
$content .= "></div>";

I then return the $content in PHP which renders that container DIV with the data attributes.

The final step (I used jQuery here, but can be straight JS) in the Javascript/jQuery is to retrieve the data atrributes which you can then use wherever you need in your Javascript code:

const feedUrl = $('#dynamic-rss').data('url');
const feedType = $('#dynamic-rss').data('feedtype');
const rows = returnInt($('#dynamic-rss').data('rows')) != NaN ? returnInt($('#dynamic-rss').data('rows')) : 10;
const cols = returnInt($('#dynamic-rss').data('cols')) != NaN ? returnInt($('#dynamic-rss').data('cols')) : 1;
const includeImage = $('#dynamic-rss').data('includeimage');
const imageAlign = $('#dynamic-rss').data('imagealign');
const imageSize = $('#dynamic-rss').data('imagesize');
const includeDate = $('#dynamic-rss').data('includedate');
const dateFormat = $('#dynamic-rss').data('dateformat');

Hope this helps anyway should anyone else stumble on this!

Here is what I figured out. In the widget code, where you create the front-end display piece, use this:

add_action('wp_footer',create_function( '', 'echo(\'<script type="text/javascript" data-id="' . $instance['widgetparamname'] . '" src="//someurl./some.js"></script>\');' ),1,0);

$instance is passed in already, and that contains the values from the widget's admin interface. So whatever value you put into the widget, will show up in that array. Then simply refer to the correct element of the array.

What this code does is ads an action to the wp_footer hook without requiring another function (to which you cannot pass any values) and thus whatever you put in here will be written in the footer area of your site.

Its worth noting that the first parameter to create_function must be empty, or wordpress will throw an error.

This is an old post and wordpress now has a very clear way to pass parameters between php and javascript. Use wp_add_inline_script() (https://developer.wordpress/reference/functions/wp_add_inline_script/)

So in this case it would be something like:

function add_my_script(){    
wp_enqueue_script('script-name','/js/example.js');
wp_add_inline_script('script-name','let data-link= 12345;','before');
}
add_action('wp_enqueue_scripts,'add_my_script');

If you're taking an option value from a plugin admin it looks like this:

wp_add_inline_script('script-name','let js-variablename="'.get_option('plugin_options'['wp_variable_name'].'";','before');

本文标签: