Adding management page functions

We now need a familiar-looking function that adds a management page to wp-admin. In this case, we use add_management_page() instead of add_submenu_page(), because this plugin is more of a tool than something that requires settings:

function modify_menu_for_searchedwords() { 
  $page = add_management_page( 
    "Capture Searched Words",  
    "Capture Searched Words",  
    'manage_options',  
    'capture_searches_new',  
    'searchedwords_page' 
  ); 
}

For this plugin, we're not going to load any custom styling or CSS files. The purpose here is to just showcase how database connection can be done, so we're going to keep everything else ultra-simple and minimal. Therefore, the only thing we have to do at this point is to write a function that retrieves the information from the database and displays it on the new management page (again, everything is done through the $wpdb objectit's a class defined by WordPress that contains a set of functions that you can use to interact with the database):

function searchedwords_page() { 
  global $wpdb; 
  $sw_table_name = $wpdb->prefix.'searchedwords'; 
 
$searched_words = $wpdb->get_results("SELECT COUNT(word) AS 
   occurrence, word FROM `$sw_table_name` GROUP BY word ORDER BY 
   occurrence DESC"); 
  ?> 
<div class="wrap" style="max-width: 600px;"> 
<h2>Searched Words</h2> 
<table class="wp-list-table widefat"> 
<thead> 
  <tr> 
    <th scope="col">Search Words</th> 
    <th scope="col"># of Searches</th> 
  </tr> 
</thead> 
<tbody> 
  <?php 
  if($searched_words !== NULL) { 
    foreach($searched_words as $searched_word) { 
      echo '<tr valign="top"><td>'.$searched_word-
         >word.'</td><td>'.$searched_word->occurrence.'</td></tr>'; 
    } 
    $searched_perfomed = true; 
  } 
  else { 
    echo '<tr valign="top"><td colspan="2"><strong>No searches 
       have been performed yet</strong></td></tr>'; 
  } 
  ?> 
</tbody> 
</table> 
</div> 
  <?php 
}

That's it. The previous plugin had more functions because data was being captured from the user and then saved. Here, that's not necessary.

Lastly, we just need to add two hooks, as follows:

add_filter('init', 'searchedwords_init'); 
add_action('admin_menu', 'modify_menu_for_searchedwords');

The first hook tells WordPress to run the initialization function when the plugin is activated, or when a search is performed. The second hook modifies the admin_menu to add a link to the new management page.

This version of the plugin is available in the code bundle for this chapterinside a subdirectory called final. It is the first and final version of the plugin.