Create page summary in widget area

Question

I am new to WordPress and I am trying to create a widget that will display a summary of my page in the widget area. The summary should contain my page’s H2 headings with links to the relevant sections using IDs and anchor tags.

First I created a filter to add IDs to my H2 tags using preg_replace_callback:

function add_ids_callback($matches) { //Callback function for preg_replace_callback
    $titles = $matches[1];
    $slug = sanitize_title_with_dashes($titles);
    return '<h2 id='.$slug.'>'.$titles.'</h2>';
}

function add_ids($content){ // Adds unique IDs to h2 titles with preg_replace_callback
    $pattern = '~<h2>(.*?)</h2>~s';
    $content = preg_replace_callback($pattern, 'add_ids_callback', $content);
    return $content;
}

add_filter('the_content', 'add_ids');

Then I extended the WP_Widget class to create a new widget:

class summary_widget extends WP_Widget{

    public function widget() {

        // Searches h2 heading with IDs using preg_match_all
        $query = get_post(get_the_ID()); 
        $content = apply_filters('the_content', $query->post_content);
        preg_match_all('~<h2.*?>(.*?)</h2>~s', $content, $match);
        $titles = $match[1];

        // Displays summary in widget area
        echo '<section id="page-summary"><h2>Summary</h2><ul>';
        foreach($titles as $value){
            echo '<li>'.$value.'</li>';
        }
        echo '</ul></section>';
    }
}

add_action( 'widgets_init', function(){
    register_widget( 'summary_widget' ); 
    }
);

This works fine but it seems very inefficient since I am parsing my content twice: one with preg_replace_callback and one with preg_match_all. Is there a way to access my $titles and $slug variables from the callback?

I have read that globalizing variables is considered bad practice and that I should return the variables I want to access as the output of a function, but since it is a callback used by pre_replace_callback, I don’t know how to do that.

Thanks for your help!

0
, , Somonus 2 years 2020-08-19T08:11:01-05:00 0 Answers 38 views 0

Leave an answer

Browse
Browse