問題描述

這個問題 here 正在問我一樣的問題,但沒有足夠的答案,也沒有選擇正確的答案,所以我再次要求,希望如果我以更一致的方式問我可能會得到回應。

我試圖實現顏色選擇器輪,如 WordPress 主題自定義 API 窗格中所示,用於選擇顏色。使用鈎子時,加載腳本和樣式可以正常工作,但是”admin_enqueue_scripts” 嘗試使用鈎子將這些腳本加載到 front-end 上,但”wp_enqueue_scripts” 不起作用。風格排隊,而不是劇本。

我想避免將文件複製到我的插件中,複製與 Wordpress 捆綁在一起的內容。必須有一種方法讓 Iris 顏色選擇器在我看不到的 front-end 上工作。

而對於那些想知道我為什麼要這樣做的人,我正在開發一個插件,在屏幕的側面添加一個 fly-out 面板,這樣就可以讓您對該站點進行即時臨時樣式更改,而無需通過 wp-admin 面板進行登錄。

最佳解決方案

這讓我瘋狂了一段時間,但是我通過在管理腳本加載器中使用完整的參數添加它們,而不是僅引用該句柄來使其工作。當我在前端打印 $wp_scripts 全局文件時,iriswp-color-picker 都無法找到,儘管它們的所有 jQuery UI 依賴項都可以工作。無論如何,不​​知道這是對的,但它完成了工作:

function wpa82718_scripts() {
    wp_enqueue_style( 'wp-color-picker' );
    wp_enqueue_script(
        'iris',
        admin_url( 'js/iris.min.js' ),
        array( 'jquery-ui-draggable', 'jquery-ui-slider', 'jquery-touch-punch' ),
        false,
        1
    );
    wp_enqueue_script(
        'wp-color-picker',
        admin_url( 'js/color-picker.min.js' ),
        array( 'iris' ),
        false,
        1
    );
    $colorpicker_l10n = array(
        'clear' => __( 'Clear' ),
        'defaultString' => __( 'Default' ),
        'pick' => __( 'Select Color' ),
        'current' => __( 'Current Color' ),
    );
    wp_localize_script( 'wp-color-picker', 'wpColorPickerL10n', $colorpicker_l10n );

}
add_action( 'wp_enqueue_scripts', 'wpa82718_scripts', 100 );

次佳解決方案

我們需要將 wp_enqueue_script 的腳本和 wp_enqueue_style 的樣式用 add_action 轉換為 functions.php 文件。這個腳本只包含一個 jQuery 文件和樣式表文件。

// Register Scripts & Styles in Admin panel
function custom_color_picker_scripts() {
wp_enqueue_style( 'wp-color-picker' );
wp_enqueue_script( 'iris', admin_url( 'js/iris.min.js' ), array( 'jquery-ui-draggable', 'jquery-ui-slider', 'jquery-touch-punch' ), false, 1 );
wp_enqueue_script( 'cp-active', plugins_url('/js/cp-active.js', __FILE__), array('jquery'), '', true );

}
add_action( 'wp_enqueue_scripts', custom_color_picker_scripts);

現在創建一個新的 JavaScript 文件,就像 cp-active.js 一樣,並使用波紋管代碼保持它的 avobe 定義的 「/js/cp-active.js」 文件路徑。

jQuery('.color-picker').iris({
// or in the data-default-color attribute on the input
defaultColor: true,
// a callback to fire whenever the color changes to a valid color
change: function(event, ui){},
// a callback to fire when the input is emptied or an invalid color
clear: function() {},
// hide the color picker controls on load
hide: true,
// show a group of common colors beneath the square
palettes: true
});

添加一個文本框到您的設置頁面與顏色選擇器的 CSS 類,您要顯示輸入文本。我使用 「color_code」 輸入 $變量。

<input id="color_code" class="color-picker" name="color_code" type="text" value="" />

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。