1 | <?php |
---|
2 | /* |
---|
3 | Plugin Name: Post Index Shortcode |
---|
4 | Plugin URI: http://jobjorn.se/ |
---|
5 | Description: Gives you a shortcode to display an alphabetized index, with a heading for each letter, either for all posts ([post-index]) or in a given category ([post-index category=ID]). For example useful if you run a cooking blog and want an index of your recipes. |
---|
6 | Version: 0.1 |
---|
7 | Author: Jobjörn Folkesson |
---|
8 | Author URI: http://jobjorn.se/ |
---|
9 | License: GPL3 |
---|
10 | */ |
---|
11 | |
---|
12 | |
---|
13 | function post_index_init() { |
---|
14 | wp_register_style('post-index-stylesheet', plugins_url() . '/post-index-shortcode/style.css'); |
---|
15 | wp_enqueue_style( 'post-index-stylesheet'); |
---|
16 | } |
---|
17 | add_action('init', 'post_index_init'); |
---|
18 | |
---|
19 | add_shortcode('post-index', 'post_index_function'); |
---|
20 | |
---|
21 | function post_index_function ($atts) { |
---|
22 | extract(shortcode_atts(array('category' => ''), $atts)); |
---|
23 | |
---|
24 | $query = array(); |
---|
25 | if(is_numeric($atts['category'])){ |
---|
26 | $query['cat'] = $atts['category']; |
---|
27 | } |
---|
28 | $query['posts_per_page'] = -1; |
---|
29 | $query['orderby'] = "title"; |
---|
30 | $query['order'] = "ASC"; |
---|
31 | |
---|
32 | $results = get_posts( $query ); // run the query |
---|
33 | |
---|
34 | $i = 0; |
---|
35 | foreach($results as $post){ |
---|
36 | $i++; |
---|
37 | if($i == 1){ |
---|
38 | echo '<div class="post-index">'; |
---|
39 | } |
---|
40 | $first_letter = strtoupper(mb_substr($post->post_title, 0, 1)); |
---|
41 | if($previous_letter != $first_letter){ |
---|
42 | if($previous_letter != ""){ |
---|
43 | echo "</ul>"; |
---|
44 | } |
---|
45 | echo "<h4>" . $first_letter . "</h4><ul>"; |
---|
46 | } |
---|
47 | echo '<li><a class="recipe_link" href="' . get_permalink($post->ID) . '" rel="bookmark">' . $post->post_title . '</a></li>'; |
---|
48 | $previous_letter = $first_letter; |
---|
49 | } |
---|
50 | if($i > 0){ |
---|
51 | echo "</ul></div>"; |
---|
52 | } |
---|
53 | |
---|
54 | return $content; |
---|
55 | } |
---|
56 | ?> |
---|