Numbering sections and block-level elements in wpautop(); WordPress as CMS for long-form writing;

You could probably achieve this with a filter of some sort on the_content.

Here’s a quick and dirty example that finds all instances of <p> and inserts a named anchor, then adds a list of links to each anchor at the top of the content.

Check out the Shortcode API as well, which could similarly allow you to add arbitrary sections with text by adding a shortcode of your own, like [section id="something"].

class InsertAnchors {
    protected $count = 0;
    protected $links="";
    public function build( $pattern, $content ) {
        $this->count = 0;
        $this->links="";
        $content = preg_replace_callback( $pattern, array( $this, '_replacer' ), $content );
        return '<p>' . $this->links . '</p>' . $content;
    }
    public function _replacer( $matches ) {
        $this->count++;
        $this->links .= '<a href="#section_' . $this->count . '">Section ' . $this->count . '</a><br>';
        return '<p><a name="section_' . $this->count . '"></a>';
    }
}

function anchors_content_filter( $content ){
    $insert = new InsertAnchors();
    return $insert->build( '~<p>~', $content );
}
add_filter( 'the_content', 'anchors_content_filter', 100 );

Leave a Comment