2013-06-20 62 views
4

試圖從帖子內容中刪除圖庫短代碼並保存在模板中其他地方使用的變量。新的Wordpress圖庫工具非常適合於選擇他們想要的圖像並分配標題,希望用它來創建圖庫,然後將其從前端內容中拉出。Wordpress刪除短代碼並保存在其他地方使用

所以這個小剪輯工作得很好,用於刪除畫廊和重新應用格式...但是我想保存該畫廊簡碼。

$content = strip_shortcodes(get_the_content()); 
$content = apply_filters('the_content', $content); 
echo $content; 

希望能保存該短碼,因此它可以被解析成一個陣列並用於重建的前端自定義庫設置。這簡碼我試圖拯救的一個例子是...

[gallery ids="1079,1073,1074,1075,1078"]

任何建議,將不勝感激。

+0

西門,確保有內容中沒有其他簡碼。 'strip_shortcodes'刪除*全部*簡碼。 – yitwail

回答

6

功能,從帖子內容搶到第一個畫廊簡碼:

// Return first gallery shortcode 
function get_shortcode_gallery ($post = 0) { 
    if ($post = get_post($post)) { 
     $post_gallery = get_post_gallery($post, false); 
     if (! empty($post_gallery)) { 
      $shortcode = "[gallery"; 
      foreach ($post_gallery as $att => $val) { 
       if ($att !== 'src') { 
        if ($att === 'size') $val = "full";  // Set custom attribute value 
        $shortcode .= " ". $att .'="'. $val .'"'; // Add attribute name and value (attribute="value") 
       } 
      } 
      $shortcode .= "]"; 
      return $shortcode; 
     } 
    } 
} 

// Example of how to use: 
echo do_shortcode(get_shortcode_gallery()); 

功能從張貼的內容刪除第一個畫廊簡碼:

// Deletes first gallery shortcode and returns content 
function strip_shortcode_gallery($content) { 
    preg_match_all('/'. get_shortcode_regex() .'/s', $content, $matches, PREG_SET_ORDER); 
    if (! empty($matches)) { 
     foreach ($matches as $shortcode) { 
      if ('gallery' === $shortcode[2]) { 
       $pos = strpos($content, $shortcode[0]); 
       if ($pos !== false) 
        return substr_replace($content, '', $pos, strlen($shortcode[0])); 
      } 
     } 
    } 
    return $content; 
} 

// Example of how to use: 
$content = strip_shortcode_gallery(get_the_content());          // Delete first gallery shortcode from post content 
$content = str_replace(']]>', ']]>', apply_filters('the_content', $content));   // Apply filter to achieve the same output that the_content() returns 
echo $content; 
0

類似$gallery = do_shortcode('[gallery]');可能工作。

2

只使用get_shortcode_regex():

<?php 
$pattern = get_shortcode_regex(); 
preg_match_all('/'.$pattern.'/s', $post->post_content, $shortcodes); 
?> 

這將返回您的內容中的所有短代碼的數組,您可以n個輸出無論你的感覺,就像這樣:

<?php 
echo do_shortcode($shortcodes[0][1]); 
?> 

同樣,你可以使用數組項,以檢查你的內容的簡併與str_replace()函數將其刪除:

<?php 
$content = $post->post_content; 
$content = str_replace($shortcodes[0][1],'',$content); 
?>