Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I need my plugin to generate the following - once per page:

<script type="text/javascript" src="https://<ritc url for js file>"></script>
<script type="text/javascript">
ritc.initialize('63864593a4153879');
</script>

The purpose of this is to allow one or more shortcodes - all requiring the same initialization - to be on a page. I can use wp_enqueue_script() in the shortcode function - this works for the first line ie.

<script type="text/javascript" src="https://<ritc url for js file>"></script>

But how do I generate the next lines to follow - and only once on the page? ie.

<script type="text/javascript">
ritc.initialize('63864593a4153879'); (one line within script tags)
</script>

Is there anything like wp_enqueue_script() but which takes a string instead of a url? The string would be the one-liner above. Not to forget the dependency on the first line above.

Or should I just generate the javascript from the shortcode function, managing it so it only appears once in the page? (How do I do this? Is there a global variable I can use?)

Or is there another approach to doing this?

Thanks in anticipation.

Colin G

share|improve this question
    
Is the number (63864593a4153879) always the same? –  vancoder Apr 26 '13 at 18:15
add comment

1 Answer

The best way to do this is to use wp_localize_script(), it serves exactly the purpose you are mentioning: passing strings to Javascript from PHP. You can do all sorts of interesting things with that: as a rule of thumb, use that when you want PHP to communicate with Javascript.

In your case you want something like this:

$ritc = array( 'initialize' => '63864593a4153879' );
wp_localize_script( '{your_script_handle}', 'ritc', $ritc );

In this way you can call ritc.initialize in your Javascript.

Be aware that you must use wp_localize_script after you have enqueued your script and passing your script $handle as a parameter.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.