2010-06-26 53 views
0

我正在研究WP中的一項功能,該功能搜索任何自定義標記<%custom-tag%>的發佈內容,並且如果它發現嘗試用具有相同名稱的文件替換該標記。一切工作正常,但是當我使用apply_filters來重新應用內容格式時,WP還添加了一些結束標籤,其中大部分爲</p>,其中一些包含HTML導致HTML格式不正確。自定義內容包括函數和apply_filters

有關如何解決此問題的任何想法?我在包含內容之前嘗試應用過濾器,但它使其更糟糕。

參見下面的功能:

//GET CUSTOM CONTENT WITH INSERTED TAGS 
function extract_custom_value($string, $start, $end){ 
    //make lower case 
    $string = strtolower($string); 
    //count how many tags 
    $count = substr_count($string, $start); 
    //create tags array 
    $custom_tags = array(); 
    if ($count >= 1) { 
     //set the initial search position to 0 
     $pos_start = -1; 
     for ($i = 0; $i < $count; $i++) { 
      //find custom tags positions 
      $pos_start = strpos($string, $start, $pos_start + 1); 
      $pos_end = strpos($string, $end, ($pos_start + strlen($start))); 
      //set start and end positions of custom tags 
      $pos1 = $pos_start + strlen($start); 
      $pos2 = $pos_end - $pos1; 
      //add to array 
      $custom_tags[$i] = substr($string, $pos1, $pos2); 
     } 
     return $custom_tags; 
    } else { 
     return false; 
    } 
} 

function get_custom_content(){ 
    //get the content from wordpress 
    $content = get_the_content(); 
    //find any custom tags 
    $custom_tags = extract_custom_value($content, '<%', '%>'); 
    //if there is custom tags 
    if ($custom_tags) { 

     foreach ($custom_tags as $tag) { 
      //make file name from tag 
      $file = TEMPLATEPATH . '/' . $tag . '.php'; 
      //check if it exists a file with the tag name 
      if (is_file($file)) { 
       //include the content of the file 
       ob_start(); 
       include $file; 
       $file_content = ob_get_contents(); 
       ob_end_clean(); 
      } else { 
       $file_content = false; 
      } 
      //replace the tag with the file contents   
      $content = str_replace('<%' . $tag . '%>', $file_content, $content); 
     } 
    } 
    //re-apply WP formating to the content 
    $content = apply_filters('the_content', $content); 
    //clean up 
    $content = str_replace(']]>', ']]&gt;', $content); 
    //show it 
    print $content; 
} 
+1

你可以不使用Wordpress短代碼API嗎? http://codex.wordpress.org/Shortcode_API – 2010-06-26 11:48:49

+0

謝謝理查德。我會看看。 – UXTE 2010-06-26 16:17:32

回答

1

由於Richard M指着我使用WP短代碼API正確的方向,我有固定的問題,現在有一個更精簡的腳本。這裏有人想知道如何:

function insert_file($atts){ 

    extract(shortcode_atts(array(
    'file' => false 
    ), $atts)); 

    if ($file == false){ 
     $file_content = false; 
    }else{ 
     $file = TEMPLATEPATH . '/' . $file . '.php'; 

     if (is_file($file)) { 
      ob_start(); 
      include $file; 
      $file_content = ob_get_contents(); 
      ob_end_clean(); 

     } else { 
      $file_content = false; 
     } 
    } 

    return $file_content; 

} 
add_shortcode('insert', 'insert_file');