Adding dynamic JS in Wordpress

I have soft rejection reason:

All scripts and styles (including comment reply) should be added from functions file and hooked with wp_enqueue_*, don’t hardcode them or include them directly, like in header.php, footer.php, etc.

Additionally, for inline styles and recommended for custom styles you can use:
https://developer.wordpress.org/reference/functions/wp_add_inline_style/
and for scripts
https://developer.wordpress.org/reference/functions/wp_add_inline_script/

So how to include dynamic generated javasrcript?
For example in the loop I have:

<script>
var = somevar;
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

somevar += <?php echo get_option( 'someoptionl' ); ?>,

<?php endwhile; ?>
<?php endif; ?>
</script>

How to add it properly?

you can use while inside
add_action( ‘wp_enqueue_scripts’, ‘mytheme_enqueue_typekit’ );

function  'mytheme_enqueue_typekit(){
if ( have_posts() ) : while ( have_posts() ) : the_post(); .........................................
}

if you don’t know how to use wp_enqueue_scripts let me know…

Bu this will force me to all loop twice - fort time to show the content, second time for generating JS.

Also it should be added from functions file, where I can’t call the loop.

I can’t see how else you can do it… sorry.

As you can see we are limited. This is what reviewer wants … it’s not the fast solution or the best solution, is just a solution

But still I don’t have an access to the_loop in functions.php

Anyone else have any idea?

Can you explain more why you’re needing a dynamic JS variable?

Sure.
I’m creating real estate theme. I have list of properties what I want to show on google map. So in the loop I add location as a javascript variable:

in loop:

<script>
lat += "<?php echo get_option('lat'); ?>,";
lng += "<?php echo get_option('lng'); ?>,";
</script>

Then in the footer I add another javascript (it’s prohibited also):

<script>
google.maps.event.addDomListener( window, 'load', map_init );
function map_init() {
       draw_map(lat,lng);
}
</script>

I think you can approach this in a different way. The answer in this stackoverflow might be a viable option for what you’re wanting to do; passing the #address text from the post(s) into an enqueued JS function.

Of course this is just a suggestion and one that I haven’t tried personally but your original method isn’t preferable.

That is interesting solution, I could add those variables as a data-lat and data-lng on some html tag. I’m also thinking about passing those data in the PHP global variable and then in footer pass them to the js script with wp_localize_script. What do you think about this approach?

I think the best approach would be using HTML5 custom data attributes.

Thank you all for help :slight_smile: