Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggregation Enquires Welcome

WordPress Post & Page Dropdown Menu

WordPress Post & Page Dropdown Menu

We're in the process of building a resource of tools to help with various developer tasks and required a menu to navigate between pages. We originally built a little dropdown menu populated from an array, but the need since presented itself for another menu to list certain posts. We wrote a little shortcode snippet that would render almost any list of posts or pages with an option to apply attributes that would filter the results via query arguments. If you're interested in seeing how we applied the feature, see this page.

Not unlike a number of other articles to filter and return certain posts, we're using the WordPress query functions.... with the exception that, in this case, we're returning the results in a dropdown menu.

The Result

The result as we applied the search feature on our tools page is as follows (selecting any option will redirect you to a new page):

We used the shortcode of [dropdown parent="8986"] (where 8986 is the parent page ID).

Because the wp_query class is so robust, we can build a menu based on any number of attributes. For example, if we chose to render the last 10 articles we could use [dropdown type="post" p="1" orderby="date" order="DESC" number="10" length="60"]. The result is as follows;

I've truncated the length of each post to 60 characters to prevent the select box from running off the screen. The alternative measure to mitigate this issue is by styling the textbox width. In the next example, we'll apply that style and select random posts tagged with wordpress. So, [dropdown type="post" p="1" orderby="random" order="DESC" number="10" length="60" tags="20" style="height: 30px; width: 500px;" text="Select Random Post"] returns:

WordPress Shortcode

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin. You may optionally download and install our plugin from the bottom of of the page.

1
<?php 
2
/*
3
 WordPress Post & Page Dropdown Menu
4
 http://www.beliefmedia.com/wp-dropdown-menu
5
*/
6
 
7
function beliefmedia_wp_post_dropdown($atts) {
8
 
9
  $atts = shortcode_atts(array(
10
    'status' => 'publish',
11
    'type' => 'page',
12
    'parent' => false,
13
    'exclude' => false,
14
    'author' => false,
15
    'category' => false,
16
    'tags' => false,
17
    'order' => 'DESC', /* ASC/DESC */
18
    'orderby' => 'date',
19
    'format' => false, /* jS F Y, g:iA */
20
    'date' => false,
21
    'number' => false,
22
    'p' => false,
23
    'style' => 'height: 35px;',
24
 
25
    /* Form search text */
26
    'text' => 'Select Page',
27
    'length' => false,
28
 
29
    /* Style */
30
    'cache' => 3600 * 8,
31
 
32
  ), $atts);
33
 
34
 $transient = 'bmdd_' . md5(serialize($atts));
35
 $cachedposts = get_transient($transient);
36
 
37
 if ($cachedposts !== false) {
38
 return $cachedposts;
39
 
40
 } else {
41
 
42
    global $post;
43
 
44
    /* Generally use this shortcode for random posts */
45
    $post_status = explode(',', $atts['status']);
46
 
47
    $args = array(
48
        'post_type' => $atts['type'],
49
        'post_status' => $post_status,
50
        'order' => $atts['order'],
51
        'orderby' => $atts['orderby'],
52
    );
53
 
54
    /* Get user ID from login username */
55
    if ($atts['author'] !== false) {
56
 
57
      /* Array of authors */
58
      $atts['author'] = explode(',', $atts['author']);
59
 
60
        /* If not numeric, get ID */
61
        foreach ($atts['author'] AS $authors) {
62
          if (!is_numeric($authors)) {
63
            $author_ob = get_user_by( 'login', $authors );
64
            $author .= $author_ob->ID . ',';
65
          } else {
66
            $author .= $authors . ',';
67
          }
68
        }
69
 
70
     /* Return string of authors */
71
     $atts['author'] =  rtrim($author, ',');
72
    }
73
 
74
    /* Post Parent? */
75
    if ($atts['parent'] !== false) $args['post_parent'] = $atts['parent'];
76
 
77
    /* Explode Posts? */
78
    if ($atts['exclude'] !== false) $args['post__not_in'] = $atts['exclude'];
79
 
80
    /* Limit authors? */
81
    if ($atts['author'] !== false) $args['author__in'] = $atts['author'];
82
 
83
    /* Limit number of posts? */
84
    $args['posts_per_page'] = ($atts['number'] !== false) ? $atts['number'] : '-1';
85
 
86
    /* Specific categories? */
87
    if ($atts['category'] !== false) $args['cat'] = $atts['category'];
88
 
89
    /* Specific tags? */
90
    if ($atts['tags'] !== false) $args['tag_id'] = $atts['tags'];
91
 
92
    /* Query */
93
    $pages = new WP_query($args);
94
 
95
    /* Build result */
96
    if ($pages->have_posts()) :
97
 
98
               $output = '
99
<form name="jump"><select name="menu" style="' . $atts['style'] . '" onchange="BMgotoPage(this)"><option value="#">' . $atts['text'] . '</option>';
100
 
101
               while ($pages->have_posts()) : $pages->the_post();
102
 
103
                   /* By default your WP time format is used */
104
                   $date = ( ($atts['format'] !== false) && ($atts['date'] !== false) ) ? get_the_date($format = $atts['format']) : get_the_date();
105
 
106
                   /* Title */
107
                   $title = get_the_title();
108
 
109
                   /* Build form option */
110
                   $output .= '<option value="' . get_permalink() . '">' . $title = ($atts['length'] !== false) ? beliefmedia_split_dropdown_string($title, $atts['length']) : $title;
111
                   if ($atts['date'] !== false) $output .= ' - ' . $date;
112
                   $output .= '</option>';
113
 
114
               endwhile;
115
               $output .= '</select></form>
116
 
117
';
118
 
119
               /* Reset query */
120
               wp_reset_postdata();
121
 
122
    else :
123
 
124
        $output = '
125
<form name="jump"><select name="menu" style="' . $atts['style'] . '" onchange="BMgotoPage(this)"><option value="#">' . $atts['text'] . ' (No Results)</option></select></form>
126
 
127
';
128
 
129
    endif;
130
 
131
    /* Wrap in p tags? */
132
    if ($atts['p'] !== false) $output = '' . $output . '';
133
 
134
    /* JS Function */
135
    $output .= '<script type="text/javascript">function BMgotoPage(select) { window.location = select.value; }</script>';
136
 
137
   /* Set transient data */
138
   set_transient($transient, $output, $atts['cache']);
139
   return $output;
140
 
141
   }
142
 
143
}
144
add_shortcode('dropdown', 'beliefmedia_wp_post_dropdown');
145
 
146
/*
147
 Split a String into Two by Character Length with PHP
148
 http://www.beliefmedia.com/php-split-string
149
*/
150
 
151
function beliefmedia_split_dropdown_string($string, $maxcharacters = '') {
152
  $string_length = strlen($string);
153
 return ($string_length > $maxcharacters) ? substr_replace($string, '...', $maxcharacters/2, $string_length - $maxcharacters) : $string;
154
}

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

Shortcode Attributes

Given the scope of the wp_query object, there are any number of queries that might be performed. We've included the most relevant search parameters to filter results.

status

There are 8 major post statuses that WordPress uses by default. The one that is likely to be used with a dropdown is publish (default). Other custom post types may also be used.

type

There are several post types that are readily available to users or internally used by the WordPress installation by default. The two that are most likely to be used are post and page (default).

parent

If displaying pages, you may nominate a parent page. Usage will display child pages.

exclude

The exclude attribute is a comma delimited list of posts or pages to exclude form results.

author

To display results by author, use the author ID or login username.

category

To limit posts by category, use the category ID.

tags

To limit return posts by tag, use the tags ID (multiple tags may be used).

order

You may order by ASC or DESC.

orderby

You may order by a large number of parameters . Most common are none, ID, author, title, name (the post slug), date, and rand (random).

format

If you include the date in the dropdown alongside the title, you may optionally alter the date presentation. While it defaults to the format defined by you in your WP installation,
you can alter with PHP's date formatting.

date

To include the date alongside the post, use date="1".

number

By default we'll return all posts, limit with number="10".

p

Wrap the result in paragraph tags with p="1". This navigates issues with WP shrotcodes and paragraph formatting.

style

Alter the style with the textbox here. For example, style="height: 30px; width: 400px;".

text

To change the text on the select box (Select Page), use text="Text in here".

length

Since post lengths can be long, you may truncate them with length="60". This uses the beliefmedia_split_dropdown_string() function.

cache

The wp_query can be an expensive operation. We cache the result for 8 hours by default. Alter in the shortcode or hardcode into the function.

Considerations

  • Read more on wp_query here . Related articles here Tag: wp_query.

Download


Title: WordPress Post & Page Dropdown Menu (WP Plugin)
Description: Displays a dropdown menu of posts or pages with shortcode. Number of parameters available to filter results.
  Download • Version 0.1, 2.5K, zip, Category: WordPress Plugins (General)
WordPress Shortcodes, (1.7K)    

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Connecticut)

  Want to have a chat?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment