[英]Run Specific Js on Specific page Wordpress
我想在特定頁面上運行特定js。 即:wwww.custom.com/english/
我嘗試了以下兩個代碼(header.php和functions.php),但它們都不起作用。
代碼1:
<script>
if(location.pathname=="/english/")
script.src = /js/custom.js;
</script>
代碼2:
function my_scripts() {
if( is_page( array( 'about-us', 'contact', 'management' ) ){
wp_enqueue_script( 'script-name', 'path/to/example.js', array(), '1.0.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
標題一根本不顯示,也沒有錯誤。 functions.php是語法錯誤。
有什么建議么? 多謝
PS:我正在使用WordPress。
您的代碼很棒! 您只是缺少右括號:
function my_scripts() {
if( is_page( array( 'about-us', 'contact', 'management' ) ) ){
wp_enqueue_script( 'script-name', 'path/to/example.js', array(), '1.0.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
為了將來參考,您可以在wp-config.php文件中將debug設置為true,我相信這會有所幫助。
還有多種其他方式。
只需打開header.php並嘗試獲取當前頁面的slug或id,並在條件肯定包含您的js的情況下放簡單
代碼1
global $post;
$post_slug=$post->post_name;
if($post_slug == 'about'){
<script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/example.js"></script>
}
或代碼2
$currentID= get_the_ID();
//instead of 10 put the your id
if($currentID == 10){
<script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/example.js"></script>
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.