简体   繁体   中英

Using PHP in External jQuery Script

In advance, JS isn't my strong suit.

I have an external .js file containing the initializing info for Smoove.JS. This file is being used in a WordPress plugin. I inserted some PHP to allow for filtering the parameters passed into the jQuery. The original file (smoove-init.js) was renamed to smoove-init.php. Everything looks good when I view the page source but nothing is actually happening. However, the script worked fine before converting to PHP. I'd really appreciate some advice.

Thanks!

UPDATE:

Big thanks to @brasofilo for his tip. For anyone interested, the final code I used to get this working is:

/**
 * Outputs filtered selectors to the Smoove.js script.
 *
 * Assigns default values to $args and checks to see if they're being filtered.
 * Adds the default/filtered selectors to a JS variable and outputs to wp_head.
 * Applies the .smoove() to the variable.
 *
 * @param  array $args Array of selectors to which .smoove() applies.
 * @param  string $selectors The string value of the $args array separated by commas.
 */
add_action( 'wp_head', 'run_smoove', 0 );
function run_smoove() {

    $args = array( 'img' );

    if ( has_filter( 'filter_smoove_args' ) ) {
        $args = apply_filters( 'filter_smoove_args', $args );
    }

    $selectors = implode( ', ', $args );

    ?>

    <script type="text/javascript">
        var my_smoove = '<?php echo $selectors; ?>';
    </script>

    <?php

}

smoove-init.js

jQuery(window).load(function () {
    jQuery( my_smoove ).smoove({
        offset  : '10%',
        moveX   : '-200px',
        moveY   : '0',
    });
});

Instead of renaming your JS, print a JS variable at the head and use it inside smoove-init.js . Something like (untested):

add_action( 'wp_head', function() { // conditional tags can be used here: codex.wordpress.org/Conditional_Tags
    $args = array( 'img', '.widget' );
    if ( has_filter( 'smoove_args' ) ) {
        $args = apply_filters( 'smoove_args', $args );
    }
    $return = implode( ', ', $args );
    ?>
    <script type="text/javascript">
        var my_smoove = '<?php echo $return; ?>';
    </script>
    <?php
}, 0 ); // priority 0, first to print

And inside the .js file:

$( my_smoove ).smoove({/*etc*/});

This is the same concept that wp_localize_script() uses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM