2016-02-11 86 views
0

我發現some code我想用我的wordpress網站中的單個頁面,但我找不到方法來做到這一點。我不是開發者,而是新手。添加特定的JavaScript代碼到wordpress頁面

我有HTML和CSS準備好了,但我不知道如何與ID 2922,每次頁面加載運行此JavaScript代碼到頁面。

$(function() { 
var parent = $("#shuffle"); 
var divs = parent.children(); 
while (divs.length) { 
    parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]); 
} 
}); 

感謝您的幫助, Thodoris

+0

https://codex.wordpress.org/Using_Javascript – gothical

+0

我不能使它發揮作用。 :/ –

回答

0

可以在footer.php編寫代碼[網站/可溼性粉劑內容/您的主題/ footer.php]

<?php if(get_the_ID()== 2922){ ?> 
<script type='text/javascript'> 
     jQuery(function() { 
      var parent = jQuery("#shuffle"); 
      var divs = parent.children(); 
      while (divs.length) { 
       parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]); 
      } 
     }); 
    </script> 

或閱讀本https://www.tipsandtricks-hq.com/how-to-add-javascript-in-a-wordpress-post-or-page-1845

+0

該腳本正在工作!感謝@Ram!我使用了不同的「如果」,因爲你的不工作。最終代碼:<?php if(is_page(3318)):?> <?php endif; ?>(ID是不同的,因爲我創建了一個新頁面)。 –

+0

腳本不能在''以下工作,但它在''之上工作。 –

0

你可以用一個有條件的,像這樣把它添加到single.php

<?php if (is_page(3318)) : ?> 
    <script type='text/javascript'> 
     $(function() { 
      var parent = $("#shuffle"); 
      var divs = parent.children(); 
      while (divs.length) { 
       parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]); 
      } 
     }); 
    </script> 
<?php endif; ?> 

這將增加,只有當它是頁面上的escript單身職位ID 3318.

編輯:增加了正確的答案,並改爲正確的ID。

+0

感謝您的幫助。我測試了你的腳本,但沒有發生任何事。這裏是網頁:http://www.fomo.gr/test-page-2/。沒有隨機的圖像順序。 –

+0

你確定ID是2911嗎?你有沒有檢查_script_是否被輸出到頁面中?你的頁面看起來有不同的ID,所以它不會添加'腳本' –

+0

我把正確的ID(3318),但仍然沒有。我的頁面使用主題的「template-fullwidth.php」。也許嘗試在那裏上面的代碼? –

0

您可以從jQuery的做到這一點。在你的腳本添加條件來檢查身體是否具有該頁面的類別id與您的page-id-2922相同,如果是,則運行該代碼。

我已經更新了你的腳本,請嘗試使用它:

$(function() { 

    if($('body').hasClass('page-id-2922') == true){ 
     var parent = $("#shuffle"); 
     var divs = parent.children(); 
     while (divs.length) { 
      parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]); 
     } 
    } 

}); 
+0

在哪裏可以放這段代碼?如你所說,如何從jQuery做到這一點? –

+0

@ThodorisKonsoulas - 只需在你寫的任何自定義js文件中使用它。 &它會工作,它不需要PHP代碼&編寫代碼,而是使用多種語言進行單一功能的標準做法。 – saadeez

相關問題