WordPress PHP function: HTML select element for posts & pages

/*
	WordPress Post & Page Dropdown Menu
	http://www.beliefmedia.com/wp-dropdown-menu
*/


function beliefmedia_wp_post_dropdown($atts) {

  $atts = shortcode_atts(array(
    'status' => 'publish',
    'type' => 'page',
    'parent' => false,
    'exclude' => false,
    'author' => false,
    'category' => false,
    'tags' => false,
    'order' => 'DESC', /* ASC/DESC */
    'orderby' => 'date',
    'format' => false, /* jS F Y, g:iA */
    'date' => false,
    'number' => false,
    'p' => false,
    'style' => 'height: 35px;',

    /* Form search text */
    'text' => 'Select Page',
    'length' => false,

    /* Style */
    'cache' => 3600 * 8,

  ), $atts);

 $transient = 'bmdd_' . md5(serialize($atts));
 $cachedposts = get_transient($transient);

 if ($cachedposts !== false) {
 return $cachedposts;

 } else {

    global $post;

    /* Generally use this shortcode for random posts */
    $post_status = explode(',', $atts['status']);

    $args = array(
        'post_type' => $atts['type'],
        'post_status' => $post_status,
        'order' => $atts['order'],
        'orderby' => $atts['orderby'],
    );

    /* Get user ID from login username */
    if ($atts['author'] !== false) {

      /* Array of authors */
      $atts['author'] = explode(',', $atts['author']);

        /* If not numeric, get ID */
        foreach ($atts['author'] AS $authors) {
          if (!is_numeric($authors)) {
            $author_ob = get_user_by( 'login', $authors );
            $author .= $author_ob->ID . ',';
          } else {
            $author .= $authors . ',';
          }
        }

     /* Return string of authors */
     $atts['author'] =  rtrim($author, ',');
    }

    /* Post Parent? */
    if ($atts['parent'] !== false) $args['post_parent'] = $atts['parent'];

    /* Explode Posts? */
    if ($atts['exclude'] !== false) $args['post__not_in'] = $atts['exclude'];

    /* Limit authors? */
    if ($atts['author'] !== false) $args['author__in'] = $atts['author'];

    /* Limit number of posts? */
    $args['posts_per_page'] = ($atts['number'] !== false) ? $atts['number'] : '-1';

    /* Specific categories? */
    if ($atts['category'] !== false) $args['cat'] = $atts['category'];

    /* Specific tags? */
    if ($atts['tags'] !== false) $args['tag_id'] = $atts['tags'];

    /* Query */
    $pages = new WP_query($args);

    /* Build result */
    if ($pages->have_posts()) :

               $output = '<form name="jump"><select name="menu" style="' . $atts['style'] . '" onchange="BMgotoPage(this)"><option value="#">' . $atts['text'] . '</option>';

               while ($pages->have_posts()) : $pages->the_post();

                   /* By default your WP time format is used */
                   $date = ( ($atts['format'] !== false) && ($atts['date'] !== false) ) ? get_the_date($format = $atts['format']) : get_the_date();

                   /* Title */
                   $title = get_the_title();

                   /* Build form option */
                   $output .= '<option value="' . get_permalink() . '">' . $title = ($atts['length'] !== false) ? beliefmedia_split_dropdown_string($title, $atts['length']) : $title;
                   if ($atts['date'] !== false) $output .= ' - ' . $date;
                   $output .= '</option>';
 
               endwhile;
               $output .= '</select></form>';

               /* Reset query */
               wp_reset_postdata();

    else :

        $output = '<form name="jump"><select name="menu" style="' . $atts['style'] . '" onchange="BMgotoPage(this)"><option value="#">' . $atts['text'] . ' (No Results)</option></select></form>';

    endif;

    /* Wrap in p tags? */
    if ($atts['p'] !== false) $output = '<p>' . $output . '</p>';

    /* JS Function */
    $output .= '<script type="text/javascript">function BMgotoPage(select) { window.location = select.value; }</script>';

   /* Set transient data */
   set_transient($transient, $output, $atts['cache']);
   return $output;

   }

}
add_shortcode('dropdown', 'beliefmedia_wp_post_dropdown');


/* 
	Split a String into Two by Character Length with PHP
	http://www.beliefmedia.com/php-split-string
*/


function beliefmedia_split_dropdown_string($string, $maxcharacters = '') {
  $string_length = strlen($string);
 return ($string_length > $maxcharacters) ? substr_replace($string, '...', $maxcharacters/2, $string_length - $maxcharacters) : $string;
}

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.

One thought on “WordPress PHP function: HTML select element for posts & pages

Leave a Reply