[英]Wordpress execute javascript file only if user is not logged in
[英]Wordpress Custom Javascript Doesn't Execute When Logged Out
我有一個帶有自定義 CSS 和 Javascript 插件的 Wordpress 站點。 我添加了自定義 javascript 以在頁面加載時將右側邊欄移動到頁面的左側。 它工作得很好......當我登錄到該站點時。
但是,當我注銷並查看站點時,javascript 根本不執行。 沒有錯誤,沒有控制台日志,什么都沒有……它根本不執行。 它可能與將window.onload
設置為自定義函數有關嗎?
這是我的代碼:
/**
* This function moves the sidebar to the left side of the page.
*/
window.onload = function () {
console.log('EXECUTE THIS');
const contentWrapper = document.getElementById('content-wrapper');
console.log('Children: ' + contentWrapper.children.length);
const firstChild = contentWrapper.children[0];
const secondChild = contentWrapper.children[1];
console.log('Will We Go In???');
if (secondChild.id === 'sidebar') {
console.log('YUP!')
contentWrapper.removeChild(secondChild);
contentWrapper.insertBefore(secondChild, firstChild);
}
};
更新:插件生成的自定義 js 文件似乎只有在我登錄時才提供。知道為什么會這樣嗎? 使用 chrome 開發工具,以下是登錄時的來源:
當我沒有登錄時:
我會手動完成。 所以在你主題的根文件夾中創建一個文件夾並命名它,讓我們說“js”。 在該文件夾中,創建一個javascript
文件並調用它,讓我們說“your_custom_script.js”並將您的腳本粘貼到那里。 所以你的主題結構是這樣的:
your_them_root_folder
|_js(folder)
|_your_custom_script.js(your script)
現在去找到你的主題的functions.php
文件並將以下代碼粘貼到那里:
add_action('wp_enqueue_scripts', 'enqueue_your_custom_scripts');
function enqueue_your_custom_scripts()
{
wp_enqueue_script('custom-script-js', get_theme_file_uri('/js/your_custom_script.js'), NULL, 1.5, TRUE);
};
這應該對logged in
和logged out
用戶都有效! 不需要第 3 方插件。
讓我知道你是否可以讓它工作!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.