Display posts as a select dropdown

The Display Posts plugin lets you create a list of posts using a wide range of query parameters. It will display the result as a bulleted list by default.

The code below will turn it into a select dropdown, and selecting a post will take you directly to that post. After adding the code to your theme, you can turn any Display Posts shortcode into a dropdown by adding wrapper="select" to the parameter list.

Example

[display-posts wrapper="select"]

Code

This code snippet goes in a core functionality plugin or Code Snippets.

/**
 * Display Posts, select open
 *
 * @param string $output Output.
 * @param array  $atts Atttributes.
 */
function be_dps_select_open( $output, $atts ) {
	if ( ! empty( $atts['wrapper'] ) && 'select' === $atts['wrapper'] ) {
		$output = '<select class="display-posts-listing" onchange="if (this.value) window.location.href=this.value">';
		$output .= '<option value="" selected disabled">Select a post</option>';
	}
	return $output;
}
add_filter( 'display_posts_shortcode_wrapper_open', 'be_dps_select_open', 10, 2 );

/**
 * Display Posts, select close
 *
 * @param string $output Output.
 * @param array  $atts Atttributes.
 */
function be_dps_select_close( $output, $atts ) {
	if ( ! empty( $atts['wrapper'] ) && 'select' === $atts['wrapper'] ) {
		$output = '</select>';
	}
	return $output;
}
add_filter( 'display_posts_shortcode_wrapper_close', 'be_dps_select_close', 10, 2 );

/**
 * Display Posts, option output
 *
 * @param string $output Output.
 * @param array  $atts Atttributes.
 */
function be_dps_option_output( $output, $atts ) {
	if ( ! empty( $atts['wrapper'] ) && 'select' === $atts['wrapper'] ) {
	 	$output = '<option value="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</option>';
	}
	return $output;
}
add_filter( 'display_posts_shortcode_output', 'be_dps_option_output', 10, 2 );

Filters used:


Published by Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributor to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.