2016-02-14 65 views
0

我想弄清楚如何從短代碼中提取值屬性對。顯然,我只關心那些用戶輸入的屬性。我被告知(通過一個簡潔的用戶),我應該可以用原生wordpress函數shortcode_atts這樣做,它被描述爲here。沒有骰子

但是,對於我的生活,我無法讓它返回值。

首先,對於我來說,我應該在每次需要使用它時向這個函數提供默認值是很奇怪的。顯然不是爲了首先提取這些值。但是無所謂。

$defaults_atts = array(
        'width' => 640, 
        'height' => 360, 
        'mp4' => '', 
        'autoplay' => '', 
        'poster' => '', 
        'src'  => '', 
        'loop'  => '', 
        'preload' => 'metadata', 
        'webm' => '' 
      ); 
      $rest = substr($post->post_content, 0, -8); // remove the closing [/video] 
      $videoattr = shortcode_atts($defaults_atts , $rest, 'video'); 

通知我使用$post->post_content因爲所有的帖子包含對視頻簡碼。我只刪除我不需要的關閉短代碼標籤。 (在你說錯了之前,我試過沒有這樣做,沒有任何變化。) post_content中的短代碼通常包含從寬度和高度到源文件,mp4或webm的屬性。在簡單情況下,它可能是這樣的:

[video width="1080" height="1920" webm="http://path/file.webm" autoplay="true"][/video] 

現在,當我測試了上面print_r($videoattr)我得到的是使用默認值的數組。

我在做什麼錯?

這裏有更多的測試,其失敗,提出以下建議:

首先我修改my_shortcode功能:

function my_shortcode($atts=array(), $content=null) { 
     $attribute = shortcode_atts(array(
        'width' => '640', 
        'height' => '360', 
        'mp4' => '', 
        'autoplay' => '', 
        'poster' => '', 
        'src'  => '', 
        'loop'  => '', 
        'preload' => 'metadata', 
        'webm' => '', 
      ), $atts); 

    /*echo '<pre>', print_r($attribute, 1),'</pre>';*/ 
    echo '<pre>', print_r($atts, 1),'</pre>'; 
    /*echo '<pre>', print_r($content, 1),'</pre>';*/ 
} 

然後我把它用......我有什麼,這是POST_CONTENT。

my_shortcode($post->post_content); 

這返回,作爲$ atts,我最初提供給該函數相同的簡碼。

據我所知,根據上面的函數,我應該有一個屬性數組,這正是我沒有的。

+0

你可以發佈你的整個代碼短代碼功能?它看起來不正確 – silver

+0

...在此之後沒有別的。所有它以前都是全局調用'$ post'和'$ posts'。我正等着'在print_r'中獲得正確的值的那一刻實現更多。這是一個在循環中調用的函數,我使用該函數來檢索發佈的視頻的網址,以便在fancybox的主頁中使用它。 (如果有意義的話) – nico

回答

1

所傳遞的簡碼的屬性被存儲在$的ATT變量,或者你的函數的第一個參數

給你一個想法,在這裏是如何工作的,

可以說你有一個這樣

[mys hello="world" print="no"]Content[/mys]

和你的PHP函數簡碼看起來像這樣,

function my_shortcode($atts=array(), $content=null) { 
    $attribute = shortcode_atts(array(
     'that' => 'is', 
     'this' => 'no', 
    ), $atts); 
    echo '<pre>', print_r($attribute, 1),'</pre>'; 
    echo '<pre>', print_r($atts, 1),'</pre>'; 
    echo '<pre>', print_r($content, 1),'</pre>'; 
} 

輸出將是

#echo '<pre>', print_r($attribute, 1),'</pre>'; 
Array (
    [that] => is 
    [this] => no 
) 
#echo '<pre>', print_r($atts, 1),'</pre>'; 
Array (
    [hello] => world 
    [print] => no 
) 
#echo '<pre>', print_r($content, 1),'</pre>'; 
Content 

$attribute是默認的屬性傳遞到函數,

$atts - 分配和發現短碼標記屬性,它將如果密鑰匹配覆蓋默認值,

$content - 短代碼內包含的內容,

+0

我不明白爲什麼這對我來說很難理解,但是......'$ atts'可以是完整的簡碼,包括括號? '因爲否則,如果我必須以其他方式自己提取屬性我不需要這個功能:) – nico

+0

不知道什麼是如此艱難,但基於您的簡碼,你可以很容易地通過''' $ atts ['width']'''width的值''atts ['height']'''height的值 - '''$ atts ['webm']'''webm的值'''$ atts ['autoplay']'''自動播放的值 – silver

+0

...當我嘗試這樣做時,我得到默認值,而不是用戶在短代碼中輸入的值。這就是整個難題<=困難的話讓我覺得不那麼愚蠢 – nico