簡體   English   中英

在WordPress函數文件中包括JS(與PHP)的最佳實踐

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

我正在構建一個自定義WordPress主題,並對WordPress和Functions.php有一個快速的問題。

我在自定義主題管理面板的一部分中運行了500行jQuery jQuery代碼位於我的functions.php文件中,在顯示自定義管理菜單頁面時調用。

理想情況下,我想將JavaScript移出functions.php文件,並使用wp_register_script + wp_enqueue_script,但我還將一些php代碼與腳本混合在一起。 見下文:

//Function that Provides Options within the Menu Page
function quz_custom_theme_options(){
  global $quz_default_colors, $quz_default_fonts;

    ?>

   <style type="text/css">';

    <?php   include('admin-style.php'); ?>

   </style>';



<script type="text/javascript">
function asf_toggle_box(element)
{
  if (jQuery(element).next('.expandable').is(':visible') )
  {
    jQuery(element).next('.expandable').fadeOut('slow', function(){
      jQuery(element).val('+ Settings');
      jQuery(element).next('.expandable').find('.indicator').val('');  
    });
  } else {
    jQuery(element).next('.expandable').fadeIn('slow', function(){
      jQuery(element).val('- Settings');
      jQuery(element).next('.expandable').find('.indicator').val('visible');  
    });
  }
}

js內的PHP示例

function quz_reset_colors(t)
  {
    var theme_name = jQuery(t).attr('id').substr(6);
    var color_fields = jQuery(t).parent().find('div.color_admin_area').find('.color-input-wrap > input[type="text"]');
    // jQuery(color_fields).css('border', '1px solid red');
    // console.log(color_fields);
    var colors = new Array();
    <?php
    foreach ($quz_default_colors as $key => $value)
    {
      echo 'var ary = new Array(\'' . implode('\',\'', $value) . '\');' . "\r\n";
      echo 'colors[\'' . $key . '\'] = ary;' . "\r\n";
    }
    ?>
    jQuery(color_fields).each(function(index, elem){
      jQuery(elem).val(colors[theme_name][index]);    
    });

處理此問題的最佳方法是什么? 我是否應該將所有JS放在單獨的php文件中並使用include('my_script.php'); 就像我在上述聲明中使用CSS一樣?

我有多種方法可以完成這項工作,但我想做到最好。 有什么想法嗎?

我在Easy Retweet WordPress插件中做了一個小技巧。

// 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');
}

希望這對您有用

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' );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM