2016-12-25 76 views
2

我找到了這個Altering registered symbols (R)的答案,我試圖實現類似的東西。創建插件,以改變整個WordPress站點TM符號

客戶端不希望TM以上標顯示,他們想要顯示爲下標的替代版本。

我試圖創建我的第一個WordPress插件來完成此任務,它將採用任何版本的符號(符號,名稱代碼,十進制代碼或十六進制代碼)並將其替換爲下標風格化版本) 。

這是我這麼遠......

<?php 
/* 
Plugin Name: Subscript the TM symbol 
Plugin URI: TBD 
Description: This is my first plugin. Client wants the TM subscript. So I'm figuring it out. :D 
Version: 0.1 
Author: Sarah Collins 
Author URI: http://sarahcollinsweb.design 
*/ 

(function($) { 
    "use strict"; 

    $(function() { 

     var replaced1 = $('').html().replace('™', '<sub>™</sub>'); 
     $('').html(replaced1; 

    }); 



    $(function() { 

     var replaced2 = $('').html().replace('&trade;', '<sub>&trade;</sub>'); 
     $('').html(replaced2); 

    }); 


    $(function() { 

     var replaced3 = $('').html().replace('&#8482;', '<sub>&#8482;</sub>'); 
     $('').html(replaced3); 

    }); 


    $(function() { 

     var replaced4 = $('').html().replace('&#x2122;', '<sub>&#x2122;</sub>'); 
     $('').html(replaced4); 

    }); 


}(jQuery)); 

?> 

:\我發現了一個致命的錯誤。我究竟做錯了什麼?

回答

0

我看到一些需要修復的東西。首先,這裏的更新版本:

<?php 
/* 
Plugin Name: Subscript the TM symbol 
Plugin URI: TBD 
Description: This is my first plugin. Client wants the TM subscript. So I'm figuring it out. :D 
Version: 0.1 
Author: Sarah Collins 
Author URI: http://sarahcollinsweb.design 
*/ 

add_action('wp_head', function() { 
    ?> 
    <script> 
     (function ($) { 
     "use strict"; 
     $(document).ready(function(){ 
      var replaced1 = $('body').html().replace('™', '<sub>™</sub>'); 
      $('body').html(replaced1); 

      var replaced2 = $('body').html().replace('&trade;', '<sub>&trade;</sub>'); 
      $('body').html(replaced2); 

      var replaced3 = $('body').html().replace('&#8482;', '<sub>&#8482;</sub>'); 
      $('body').html(replaced3); 

      var replaced4 = $('body').html().replace('&#x2122;', '<sub>&#x2122;</sub>'); 
      $('body').html(replaced4); 
     }); 
     }(jQuery)); 
    </script> 
    <? 
}); 

而這裏的變化:

  1. 您在混合PHP和JavaScript,這是沒有好。 Javascript是在用戶的Web瀏覽器中運行的代碼,因此您需要實際輸出代碼。在上面的代碼中,PHP解釋器實際上是在試圖運行該JavaScript代碼,這絕對不會奏效 - 答案是將事情分開,稍後我將解釋。

  2. 取而代之,要使您的想法有效,您必須使用WordPress's actions。將動作視爲WordPress處理請求併爲訪問者生成頁面時發生的事件會很有幫助,而且WordPress爲您提供了一個機會來做一些事情 - 任何事情!在這種情況下,您希望將一些JavaScript添加到HTML文檔的<head>,並且您要掛鉤的操作是wp_head action。 (僅供參考,WordPress有幾十個動作可供使用,甚至可以使用make your own - 但這已經變得更加先進了,但這只是WordPress允許插件/主題運行自定義代碼的基本機制。 )

  3. 我簡化了JavaScript代碼並刪除了幾個(function(){}(...))包裝器;那些沒有做任何事情來讓你的代碼更有效率。我想你可能只是複製/粘貼了你在這裏建立的一部分內容,但是可以減少/刪除它。

  4. 同樣在JavaScript中,我將代碼包裝在$(document).ready()回調中;這是爲了讓您的代碼不會運行,直到頁面準備就緒。這很重要,否則你的代碼會在加載後立即運行,這可能無法完全正確 - 你應該一直等到文檔準備就緒,然後才能處理頁面的文本/ html內容。

正如一個側面說明,有些人可能會指出,這不是使用jQuery的最有效的方式 - 但我認爲現在可以跳過這一點!主要只是試圖演示如何從WordPress插件運行JavaScript,所以給這個鏡頭,讓我們知道是否有任何問題/問題。