基金会麦哲伦自动生成

时间:2015-07-08 07:46:25

标签: php wordpress zurb-foundation

我想在h3标签的子页面上自动生成magellan。 为此我尝试了jameswlane脚本(https://gist.github.com/jameswlane/f1eabeedf430ef67318d),我只将h2标签更改为h3。我似乎不太了解这段代码。

我认为我只需要在wordpress主题的header.php文件中粘贴此代码,它会自动扫描h3标签的DOM内容,但它没有。

没有任何东西出现,甚至是空的div。

将以下行用作init:

<?php $tag = 'h3'; $html = get_the_content(); $items = getTextBetweenTags( $tag, $html ); ?>

我可以请你就此事提出建议吗?

<?php

function getTextBetweenTags($tag, $html, $strict=0) {
$dom = new domDocument;
if($strict==1) {
    $dom->loadXML($html);
} else {
    $dom->loadHTML($html);
}
$dom->preserveWhiteSpace = false;
$content = $dom->getElementsByTagname($tag);
$out = array();
foreach ($content as $item) {
    $out[] = $item->nodeValue;
}
return $out;
}

function create_slug($string){
$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
return $slug;
}

function create_magellan($items){
$output .= '<div data-magellan-expedition="fixed">' . PHP_EOL;
$output .= '<dl class="sub-nav">' . PHP_EOL;
foreach( $items as $item ) {
    $output .= '<dd data-magellan-arrival="' . create_slug( $item ) . '"><a href="#' . create_slug( $item ) . '">' . $item . '</a></dd>';
}
$output .= '</dl>' . PHP_EOL;
$output .= '</div>' . PHP_EOL;
add_filter('the_content', 'my_formatter', 99);
echo $output;
}

function my_formatter($content) {
$new_content = '';
$tag = 'h3';
$pattern_full = '{(<' . $tag . '>.*?</' . $tag . '>)}is';
$pattern_contents = '{<' . $tag . '>(.*?)</' . $tag . '>}is';
$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);

foreach ($pieces as $piece) {
    if (preg_match($pattern_contents, $piece, $matches)) {
        $test = $matches[1];
        $new_content .= '<a name="'.create_slug($test).'"></a>'.PHP_EOL.'<'.$tag.' data-magellan-destination="'.create_slug($test).'">'.$test.'</'.$tag.'>'.PHP_EOL;
    } else {
        $new_content .= wptexturize(wpautop($piece));
    }
}
return $new_content;
}

?>

修改

有些工作并返回错误:

Warning: DOMDocument::loadHTML(): Empty string supplied as input in /www/ilee_www/www/2.goldbaltic/dev.goldbaltic.pl/wp-content/themes/dermiclab_fs/partials/2.Nav/mainNav.php on line 47

我文件中的第47行是

$dom->loadHTML($html);

 function getTextBetweenTags($tag, $html, $strict=0) {
    $dom = new domDocument;
    if($strict==1) {
        $dom->loadXML($html);
    } else {
        $dom->loadHTML($html);
    }
    $dom->preserveWhiteSpace = false;
    $content = $dom->getElementsByTagname($tag);
    $out = array();
    foreach ($content as $item) {
        $out[] = $item->nodeValue;
    }
    return $out;
}

0 个答案:

没有答案
相关问题