Viewing 1 replies (of 1 total)
  • Thread Starter Joy

    (@joyously)

    I put some working code on the previously mentioned topic. I’ll paste it here also.

    /**
     * Substitute a Table of Contents for the excerpt if there are more than 2 headings.
     */
    function my_excerpt_TOC ( $text, $num_words, $more, $original_text ) {
      $many = preg_match_all( "/(<(h[\w]+)[^>]*>)(.*)(<\/\\2>)/", $original_text, $matches, PREG_SET_ORDER );
      $out = '';
      if ( $many > 2 ) {
        foreach ($matches as $val) {
          $level = intval( ltrim( $val[2], 'h' ) );
          if ( isset( $save ) ) {
            $out .= ( $save > $level ) ? '</li>' . str_repeat( '</ul></li>', $save-$level ) 
              : ( ( $save < $level ) ? str_repeat( '<ul>', $level-$save ) : '</li>' );
          }
          else $first = $level;
          $save = $level;
          $out .=  '<li>' . $val[3];
        }
        return '<ul>' . $out . '</li>' . str_repeat( '</ul></li>', $level-$first ) . '</ul>';
      }
      return $text;
    }
    add_filter( 'wp_trim_words', 'my_excerpt_TOC', 11, 4 );
Viewing 1 replies (of 1 total)
  • The topic ‘Feature Request: option to use the TOC as excerpt’ is closed to new replies.