我有两个WordPress短代码,我正在处理:
规格:
我想使用一个静态toc数组在每个章节标记上添加章节,然后将其输出到toc短代码中。唉,toc短代码可以出现在章节之前,然后数组将为空。
下面的post html将不显示toc:
[toc][/toc]
Here is some content
[chapter name="hello"]xxx[/chapter]
In between content may come here
[chapter name="world"]yyy[/chapter]
Some more stuff这是我的起始代码(嵌入在类中):
public static function register_chapter_shortcode($atts, $content=null){
$atts = shortcode_atts (
array (
'name' => '',
), $atts );
$name = $atts["name"];
if (self::$toc == null){
self::$toc = array ($name);
} else {
array_push(self::$toc, $name);
}
return '
<h2>'.$atts["name"].'</h2>
<div>'.do_shortcode($content).'</div>'
;
}
public static function register_toc_shortcode($atts, $content=null){
$items = "";
foreach (self::$toc as $item){
$items = $items. '<li><a href="#">'.$item.'</a></li>';
}
return '
<ul>'.$items.'</ul>
';
}发布于 2017-09-21 08:26:43
问题是函数运行的顺序:register_toc_shortcode在register_chapter_shortcode设置self::$toc之前运行,所以它没有显示。这意味着[toc]必须紧跟在[chapter]短代码之后。问题是,您需要在列出章节之前显示TOC。
正如我在评论中提到的,我可以看到两种解决方法--一种是使用javascript将TOC插入到DOM中,但如果可能的话,我会避免这样做。
另一种方法是使用register_chapter_shortcode将所有内容存储在self::$toc中,而不输出任何本身。然后register_toc_shortcode可以显示所有内容。
这还没有经过测试,但是它背后的基本逻辑应该是正确的:
public static function register_chapter_shortcode($atts, $content=null){
$atts = shortcode_atts (
array (
'name' => '',
), $atts );
if (self::$toc == null)
self::$toc = array ();
/* add ALL info to self::$toc in an array */
array_push(self::$toc, array("name" => $atts["name"], "content" => $content));
}
public static function register_toc_shortcode($atts, $content=null){
/* add the ability to pass in the position of the toc, as required in your comment */
$atts = shortcode_atts (
array (
'position' => 'top', /* e.g. "top" (default), "bottom", "both" */
), $atts );
/* generate the HTML for the TOC */
$toc_html = "<ul>";
foreach (self::$toc as $item){
$toc_html .= '<li><a href="#">'.$item["name"].'</a></li>';
}
$toc_html .= "</ul>";
/* generate the HTML for the chapters */
$chapters = "";
foreach (self::$toc as $item){
$chapters .= '<h2>'.$item["name"].'</h2>
<div>'.do_shortcode($item["content").'</div>';
}
/* generate the output, putting the TOC at the top or bottom as required */
$html = "";
if ($position == "top" || $position == "both") $html .= $toc_html;
$html .= $chapters;
if ($position == "bottom" || $position == "both") $html .= $toc_html;
return $html;
}然后您可以按以下方式使用它:
[chapter name="hello"]xxx[/chapter]
[chapter name="world"]yyy[/chapter]
[toc position="top"][/toc]注意:[toc]总是必须跟踪chapter,以便为[toc]设置它们以显示详细信息。
https://stackoverflow.com/questions/46338071
复制相似问题