Skip to content

Instantly share code, notes, and snippets.

@dingo-d
Created Oct 7, 2016
Embed
What would you like to do?
A simple filter for hours custom post type, that throws an error linked to trac ticket https://core.trac.wordpress.org/ticket/30013.
add_action('restrict_manage_posts', 'filter_hours_post_by_user');
/**
* Display a custom dropdown in hours page (filter)
*
* Filters posts only by one user.
*
* @since 1.0.0
*/
function filter_hours_post_by_user() {
$type = 'hours';
if ( isset( $_GET['post_type'] ) ) {
$type = $_GET['post_type'];
}
if ( 'hours' === $type ) {
global $wpdb;
$users_sql_query = "SELECT $wpdb->users.*, $wpdb->postmeta.* FROM $wpdb->users LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.meta_value = $wpdb->users.ID WHERE $wpdb->postmeta.meta_key = 'user_id' GROUP BY $wpdb->users.ID";
$user_results = $wpdb->get_results( $users_sql_query, ARRAY_A );
$values = array();
foreach ( $user_results as $user_key) {
$values[$user_key['ID']] = $user_key['display_name'];
}
?>
<label class="screen-reader-text" for="user_id"><?php esc_html_e( 'Filter by Users', 'mycustom' ); ?></label>
<select name="user_id" id="user_id">
<option value=""><?php esc_html_e( 'All Users', 'mycustom' ); ?></option>
<?php
$current_v = isset( $_GET['user_id'] ) ? $_GET['user_id']:'';
foreach ( $values as $value => $label ) {
print_r(gettype($value));
printf(
'<option value="%s" %s>%s</option>',
$value,
selected( $value == $current_v, true, false ),
$label
);
}
?>
</select>
<?php
}
}
add_filter( 'parse_query', 'mycustom_hours_filter' );
/**
* If submitted filter by post meta
*
* @param object $query wp_query object.
*
* @return Void
*/
function mycustom_hours_filter( $query ) {
global $pagenow;
if ( ( isset( $_GET['post_type'] ) && 'hours' === $_GET['post_type'] ) && is_admin() && $pagenow == 'edit.php' && isset( $_GET['user_id'] ) && $_GET['user_id'] != '') {
$query->query_vars['meta_key'] = 'user_id';
$query->query_vars['meta_value'] = (string) $_GET['user_id'];
// error_log( print_r($query, true) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment