Last active
February 22, 2016 20:30
-
-
Save kylephillips/aa833a080ba5dd713948 to your computer and use it in GitHub Desktop.
Create a sortable state column with state dropdown using simple locator data.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Set the Location Columns | |
* @param array $columns | |
*/ | |
function locationColumns($columns) | |
{ | |
$columns['wpsl_state'] = 'State'; | |
return $columns; | |
} | |
add_filter('manage_edit-location_columns', 'locationColumns'); | |
/** | |
* Set the Custom Sortable Columns | |
* @param array $columns | |
*/ | |
function setSortableLocationColumns($columns) | |
{ | |
$columns['wpsl_state'] = 'State'; | |
return $columns; | |
} | |
add_filter('manage_edit-location_sortable_columns', 'setSortableLocationColumns'); | |
/** | |
* Custom Column Data | |
*/ | |
function locationColumnData($column, $post_id) | |
{ | |
if ( $column !== 'wpsl_state' ) return; | |
$state = get_post_meta($post_id, 'wpsl_state', true); | |
echo $state; | |
} | |
add_action('manage_location_posts_custom_column', 'locationColumnData', 10, 2); | |
/** | |
* Add the State select filter to locations (Creates dropdown select menu with all states) | |
*/ | |
function addStateSelect() | |
{ | |
global $typenow; | |
if ( $typenow !== 'location' ) return; | |
// Get all the unique states | |
global $wpdb; | |
$all_states = $wpdb->get_results("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'wpsl_state'"); | |
$current = ( isset($_GET['wpsl_state']) ) ? $_GET['wpsl_state'] : ''; | |
$out = '<select name="wpsl_state">'; | |
$out .= '<option value="">' . __('All States', 'textdomain') . '</option>'; | |
foreach ( $all_states as $state ){ | |
$out .= '<option value="' . $state->meta_value . '"'; | |
if ( $state->meta_value == $current ) $out .= ' selected'; | |
$out .= '>' . $state->meta_value . '</option>'; | |
} | |
$out .= '</select>'; | |
echo $out; | |
} | |
add_action('restrict_manage_posts', 'addStateSelect'); | |
/** | |
* Add the State Filter to the Posts | |
*/ | |
function addStateFilter($query) | |
{ | |
global $typenow; | |
if ( !is_admin() && !is_main_query() ) return; | |
if ( $typenow !== 'location' ) return; | |
if ( !isset($_GET['wpsl_state']) ) return; | |
$query->set('meta_key', 'wpsl_state'); | |
$query->set('meta_value', sanitize_text_field($_GET['wpsl_state'])); | |
} | |
add_action( 'pre_get_posts', 'addStateFilter' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment