2017-05-31 123 views
1

我正在使用wordpress重做客戶端網站。他們以前的開發人員從零開始編寫網站,在管理部分中對產品進行文本編輯時,在sku /產品ID號前加上了帶有散列/英鎊符號「#」的產品sku/product id,以創建鏈接到現有產品。我想知道什麼語言和代碼可能是什麼樣子,所以我可以成功地做基本相同的事情。我已經在WooCommerce中創建了使用SKU /產品ID的所有產品的統一短鏈接。Wordpress#創建產品鏈接

例如:#7512D將創建一個鏈接如下;

<a href="bioquip.com/search/dispproduct.asp?pid=7512D">7512D</a> 
+1

這裏有很多問題:你爲什麼想知道使用哪種語言?您已經在使用PHP的聲音中解決了WordPress的問題,因爲我相信您知道。代碼縮減了你分享的內容,但在URL中有一個'asp'擴展名。不知道該怎麼做! –

+0

該網站是我們最終更新的一個非常舊的網站。我們決定使用Wordpress進行更簡單的自定義和功能。 – bworkman

+0

明白了 - 你正在尋找複製WordPress內的舊功能? –

回答

2

這應該作爲一個插件,以保持它的主題獨立,它只需要過濾帖子(或頁面)的「內容」。這是一個使用WooCommerce的示例。它使用與您在文章(#XXXXXX)中提到的相同的設計,但我建議您找到除「#」以外的其他內容作爲比賽的開始。這將匹配格式爲&#8217;格式的所有HTML編碼字符。雖然SKU查找可以確保您不會有錯誤的匹配,但這意味着會有比查詢需要更多的查詢。

<?php 

/* 
Plugin Name: Replace SKU with Link 
Description: Plugin to replace a formatted SKU (#XXXXXX) with the link to that product 
Version: 1.0 
*/ 

defined('ABSPATH') or die('No direct access!'); 

class SkuReplace { 

    /* 
    * On __construct, we will initialize the filter for the content 
    */ 
    function __construct() 
    { 
     add_filter('the_content', array($this, 'replace_sku_with_link')); 
    } 

    /** 
    * The filter hook get processed here 
    * 
    * @return string the filtered content 
    */ 
    function replace_sku_with_link($content) 
    { 

     // Check if we're inside the main loop in a single post page. 
     if ((is_single() || is_page()) && in_the_loop() && is_main_query()) 
     { 
      // Use the callback to check to see if this product exists in the DB 
      $content = preg_replace_callback(
       '/\#[^\s\<]*/', 
       array($this, 'get_product_url'), 
       $content 
      ); 
     } 

     return $content; 
    } 

    /** 
    * The match is checked against the product entries to verify that it exists 
    * If it does, it will create the hyperlink and return it, else, it returns 
    * the original string so as not to break the content 
    * 
    * @return string URL or original string 
    */ 
    function get_product_url($in) 
    { 
     global $wpdb; 

     $sku = ltrim(rtrim($in[0], " \t\r\n"), '#'); 

     $product_id = $wpdb->get_var(
      $wpdb->prepare(
       "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", 
       $sku 
      ) 
     ); 

     if($product_id) 
     { 
      $product = new WC_Product($product_id); 

      $url = get_permalink($product_id) ; 

      return '<a href="'. $url .'">'. $product->get_name() .'</a>'; 
     } 

     return $in[0]; 
    } 

} // end class 

$plugin_name = new SkuReplace(); 
+0

感謝您的反饋!我發現它打破了單一產品頁面。像'@'這樣的另一個符號會比'#'更好嗎?如果是這樣的話,我會替換上面php中出現的'#'嗎? – bworkman

+0

如果它打破了頁面,那麼它可能與其他插件衝突。您可以嘗試關閉其他插件,直到看到它正在運行以查看衝突是什麼。您可能需要調整'add_filter()'調用的時間。 –

+0

我已經停用了所有插件,並且如果描述文本中有一個#用於創建鏈接,則所有描述都將不會加載,並且管理員wp標題爲空。 – bworkman