mercredi 28 janvier 2015

Do a summary based on sections in a post


I wonder if it's possible in wordpress to create a summary, let's say at the begining of the post, that displays links to all the post section ?


Example:



[summary title="Summary"]

[section]Title 1[/section]
Content

[section]Title 2[/section]
Content


would display :



Summary
- Title 1
- Title 2

Title 1
Content

Title 2
Content


What I tried is to define shortcodes [section] (that add a section to an array $sections for example) and [summary] (that iterate over $sections and display all titles). The problem is that I have access to all section items only at the end of the post (i.e. when all [section] have been parsed I suppose). If I put [summary] at the begining of the post, nothing appears.


Here is the code of myplugin.php:



$section_id = 1;
$summary = array();

//
add_shortcode('dc:summary', function($attr)
{
global $summary;

$title = isset($attr['title'])? $attr['title'] : 'Summary';

$html = '<div>';
$html .= '<h1>' . $title . '</h1>';
$html .= '<ol>';
foreach($summary as $title)
{
$html .= '<li><a href="#{section_anchor}">'.$title.'</a></li>';
}
$html .= '</ol></div>';
return $html;
});

//
add_shortcode('dc:section', function($attr, $content = '')
{
global $section_id, $summary;
$html = '<h1>'.$section_id . '. ' . $content.'</h1>';
$summary[$section_id] = $content;
$section_id++;
return $html;
});


The code of the post:



[dc:summary title="First summary"]

[dc:section]Title 1[/dc:section]
Content

[dc:section]Title 2[/dc:section]
Content

[dc:summary title="Last summary"]


And the link to the post: http://ift.tt/1zxPLaO


Is there a way to order shortcode parsing ? or another way to implement this functionality ?


Thanks





Aucun commentaire:

Enregistrer un commentaire