Best Practice for Including JS (with PHP) in WordPress Functions file

£可爱£侵袭症+ 提交于 2019-12-03 16:14:10

I do a small trick to do this in my Easy Retweet WordPress Plugin.

// Enqueue the script
add_action('template_redirect', 'add_script');

function add_script() {
    wp_enqueue_script('retweet', get_option('home') . '/?retweetjs');
}

add_action('init', 'deliver_js');

function deliver_js() {
    if ( array_key_exists('retweetjs', $_GET) ) {

        header('Content-Type: text/javascript');
        print_retweet_js($options);

        // die after printing js
        die();
    }
}

function print_retweet_js($options) {
     include_once('path/to/your/js/script.php');
}

Hope this is useful to you

function theme_script() {
?>
    < script type="text / javascript" >
      here is your script
    < /script >
<?php
 wp_enqueue_script( 'theme_script_id', get_bloginfo('template_directory').'/js/theme_script.js', array( 'jquery' ) );
}
 add_action( 'wp_print_scripts', 'theme_script' );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!