Shortcode Function to List Post Titles

The code below can be added to your functions.php to provide a shortcode which will list post titles.

When you add the code to functions.php, you must be careful, because any errors will make your site unusable.  BACK UP your functions.php before adding this, and make sure that you know how to restore from the backup.

If your functions.php file ends with ‘?>’, just paste the entire code on the line following it.  If it does not end in ‘?>’, remove the ‘<?php’ line and the ‘?>’ line from the code below before pasting it in.

Once the code has been added to functions.php with no errors, create a new Page to display your titles.  Enter any content you want on the page.  Where you want the list of titles to show, enter the shortcode as shown in the comments in the code.

<?php
/* Shortcode to list post titles
   Usage: [ mam_list_post_titles (posts_per_page=n) ]
*/
function mam_list_post_titles($atts) {
   global $wpdb;
   extract(shortcode_atts(array(
      'posts_per_page' => get_option('posts_per_page'),
   ), $atts));

   if (!($posts_per_page = intval($posts_per_page))) $posts_per_page = 10;
   $current = (intval($_GET['mypage'])) ? intval($_GET['mypage']) : 1;
   $offset = ($current - 1) * $posts_per_page;
   $op = '';

   $sql = "SELECT SQL_CALC_FOUND_ROWS ID, post_title FROM $wpdb->posts
      WHERE post_type = 'post' AND post_status = 'publish'
      LIMIT $offset,$posts_per_page";
   $rows = $wpdb->get_results($sql);
   $found = $wpdb->get_var("SELECT FOUND_ROWS()");

   // echo "<p>SQL:$sql</p>";
   // echo "<p>PPP:$posts_per_page  CURR:$current  OFF:$offset  FOUND:$found</p>";

   $pagination_args = array(
      'base' => @add_query_arg('mypage','%#%'),
      'format' => '',
      'total' => ceil($found/$posts_per_page),
      'current' => $current,
      'show_all' => false,
      'type' => 'array',
   );

   if ( is_array($pages = paginate_links($pagination_args) )) {
      $links = "\n<pre>" . implode('&nbsp;&nbsp;',$pages) . "</pre>\n";
      $op .= $links;
   }

   $op .= "\n<ul class='mam_post_titles'>";
   foreach ($rows as $row ) {
      $op .= "\n<li><a href='" . get_permalink($row->ID) . "' rel='bookmark' title='Permanent Link to " . sanitize_title($row->post_title) . "'>$row->post_title</a></li>";
   }
   $op .= "\n</ul>\n";
   $op .= $links;
   return $op;
}
add_shortcode('mam_list_post_titles','mam_list_post_titles');
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

*