Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a PHP variable to a JavaScript function in WordPress?

I'm trying to pass an element ID value to add_action(), which on its turn sets up the JS for Slick Slider in the footer.

The result I get is:

$("#").slick({...

But what I want is:

$("#rtt_grid_carrousel_5bd9bbeabd625").slick({...

This is my code so far:

$uniqid = uniqid('rtt_grid_carrousel_');
js_rtt_grid_carrousel( $uniqid );


function js_rtt_grid_carrousel( $uniqid ) {
    add_action('wp_footer', function( $uniqid ) {
        ?>
            <script id="rtt_grid_carrousel" type="text/javascript">
                $(document).ready(function () {
                    $("#<?php echo $uniqid ?>").slick({
                        dots: false,
                        arrows: false,
                        infinite: false,
                        slidesToShow: 1,
                        slidesToScroll: 1,
                        draggable: false,
                        vertical: false,
                        centerMode: false,
                        adaptiveHeight: true,
                        // fade: true,
                        // cssEase: "linear",
                    });


                });
            </script>
        <?php
    });
}

--EDIT-- Edit for along the road. So, we've found out the php var does gets passed to

 js_rtt_grid_carrousel()

But not to

add_action('wp_footer', function(){...}); inside that function
like image 466
Tim Avatar asked Apr 07 '26 18:04

Tim


1 Answers

Ah! I found it! :) You guys gave me some stuff to think about. And searching along I found this here. .

$uniqid = uniqid('rtt_grid_carrousel_');
js_rtt_grid_carrousel( $uniqid );


function js_rtt_grid_carrousel( $uniqid ) {
    add_action('wp_footer', function() use ( $uniqid ) {
        ?>
            <script id="rtt_grid_carrousel" type="text/javascript">
                $(document).ready(function () {
                    $("#<?php echo $uniqid ?>").slick({
                        dots: false,
                        arrows: false,
                        infinite: false,
                        slidesToShow: 1,
                        slidesToScroll: 1,
                        draggable: false,
                        vertical: false,
                        centerMode: false,
                        adaptiveHeight: true,
                        // fade: true,
                        // cssEase: "linear",
                    });


                });
            </script>
        <?php
    });
}

Focus on the "use" in:

add_action('wp_footer', function() use ( $uniqid ) {...});

I'll have to look more into "use" to see what this is, but it works! :) Thanks all!

like image 153
Tim Avatar answered Apr 10 '26 09:04

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!