關於 WordPress Shortcode 使用觀念及設計事項

行動版 for , 瀏覽人次: 840  , SSL Connection SSL
  • 1.  關於Shortcode:

    顧名思義,就是讓編輯者可以用最少的負擔來呈現內容。一行簡短的Shortcode可以帶出完整的內容。
    例如這樣:
    [game_info id="304205" e="這是評論...."]

     

    2.  文章:

    我們針對文章進行訊息擴散,單篇文章的內容顯得很重要,Shortcode可以豐富文章本體,並讓文章內容更具可看性。

     

    當the_content開始呈現,shortcode會被解析,並依照既有的設計呈現內容。

    因此,當我們編輯文章:[game_info id="298367"],在資料庫中,存入的也會是:[game_info id="298367"],當文章內容呈現時,才會呈現實際內容。

     

     

    3.  Shortcode的註冊名稱:

    就像分類一樣,我們註冊一個Shortcode時,不可以用一些系統內定的字眼,例如: , , [gallery] and 。

     

    4.  新增一個Shortcode,兩個簡單的例子:

    // [book]

    add_shortcode( ‘book’, ‘app_book’ );function app_book() {  return ‘ < a href=”http://www.amazon.com/dp/0470560541” > book < /a > ’;  }

     

    // [bartag foo="foo-value"]

    function bartag_func( $atts ) {

    extract( shortcode_atts( array(

    ‘foo’ => ‘something’,

    ‘bar’ => ‘something else’,

    ), $atts ) );

     

    return “foo = {$foo}";

    }

    add_shortcode( ‘bartag’, ‘bartag_func’ );

    Shortcode的名稱,$atts的attribute names 都全部用小寫,shortcode_atts中可以設定預設值。

     

    Shortcode的返回值應該用 return 而不要用 echo 。

     

    5.  Shortcode的兩種類型

    self-closing:[bartag foo="foo-value"]

    Enclosing:[myshortcode]content[/myshortcode]

     

    Enclosing shortcode 的一個簡單的例子:

    function caption_shortcode( $atts, $content = null ) {     return '<span>' . $content . '</span>';  }  add_shortcode( 'caption', 'caption_shortcode' );

    使用方式:

      [caption]My Caption

    辨識self-closing和Enclosing shortcode的方式,看傳入值有沒有$content = null。

     

     

    6.  Shortcode的Function 與其它用法

    function add_shortcode($tag, $func)  新增Shortcode

    function remove_shortcode($tag)  移除Shortcode

    function remove_all_shortcodes()  移除所有Shortcode

    function shortcode_atts($pairs, $atts) 指定屬性的預設值到$atts中

    do_shortcode( $content ) 執行已知的Shortcode

     

    echo do_shortcode('');

     

    $return = do_shortcode($content); // 不echo, 把結果指定給變數

     

    <a href="[permalink id=49]">Basic Usage</a>        // 在程式碼中置入
回 文章列表頁