問題描述
這個問題 here 正在問我一樣的問題,但沒有足夠的答案,也沒有選擇正確的答案,所以我再次要求,希望如果我以更一致的方式問我可能會得到回應。
我試圖實現顏色選擇器輪,如 WordPress 主題自定義 API 窗格中所示,用於選擇顏色。使用鉤子時,載入指令碼和樣式可以正常工作,但是”admin_enqueue_scripts” 嘗試使用鉤子將這些指令碼載入到 front-end 上,但”wp_enqueue_scripts” 不起作用。風格排隊,而不是劇本。
我想避免將檔案複製到我的外掛中,複製與 Wordpress 捆綁在一起的內容。必須有一種方法讓 Iris 顏色選擇器在我看不到的 front-end 上工作。
而對於那些想知道我為什麼要這樣做的人,我正在開發一個外掛,在螢幕的側面新增一個 fly-out 面板,這樣就可以讓您對該站點進行即時臨時樣式更改,而無需透過 wp-admin 面板進行登入。
最佳解決方案
這讓我瘋狂了一段時間,但是我透過在管理指令碼載入器中使用完整的引數新增它們,而不是僅引用該控制程式碼來使其工作。當我在前端列印 $wp_scripts 全域性檔案時,iris 和 wp-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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。