自定义内容包括function和apply_filters

时间:2010-06-26 10:43:38

标签: wordpress

我正在使用WP中的一个函数,该函数在帖子内容中搜索任何自定义标记<%custom-tag%>,如果它发现尝试用同名文件替换标记。一切正常但是当我使用apply_filters重新应用内容格式时,WP还会添加一些结束标记,主要是</p>在一些包含的HTML中,导致HTML格式错误。

关于如何解决此问题的任何想法?我尝试在包含内容之前应用过滤器,但这会让情况变得更糟。

见下面的功能:

//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 个答案:

答案 0 :(得分: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');