Skip to content

Instantly share code, notes, and snippets.

@vishalkakadiya
Created September 24, 2021 15:22
Show Gist options
  • Save vishalkakadiya/bf592778ed7387caf1107f328b0e0158 to your computer and use it in GitHub Desktop.
Save vishalkakadiya/bf592778ed7387caf1107f328b0e0158 to your computer and use it in GitHub Desktop.
WordPress - Add custom filers on backend admin post listing
/**
* Add custom filters.
*/
function custom_filters() {
$post_type = filter_input( INPUT_GET, 'post_type', FILTER_SANITIZE_STRING );
// Only add filter to post type you want.
if ( 'POST_TYPE_NAME' === $post_type ) {
$selected_zone = filter_input( INPUT_GET, 'filter_content_zone', FILTER_SANITIZE_STRING );
?>
<select name="filter_content_zone">
<option value="all"><?php esc_html_e( 'All Content Zones', 'TEXT_DOMAIN' ); ?></option>
<option value="past" <?php selected( $selected_zone, 'past' ); ?>><?php esc_html_e( 'Past Zones', 'TEXT_DOMAIN' ); ?></option>
<option value="current" <?php selected( $selected_zone, 'current' ); ?>><?php esc_html_e( 'Current Zones', 'TEXT_DOMAIN' ); ?></option>
<option value="future" <?php selected( $selected_zone, 'future' ); ?>><?php esc_html_e( 'Future Zones', 'TEXT_DOMAIN' ); ?></option>
</select>
<?php
}
}
add_action( 'restrict_manage_posts', 'custom_filters' );
/**
* Manage filtering data.
*
* @param \WP_Query $query WP_Query object.
*/
function parse_query( $query ) {
if ( is_admin() && 'POST_TYPE_NAME' === $query->query['post_type'] ) {
$selected_zone = filter_input( INPUT_GET, 'filter_content_zone', FILTER_SANITIZE_STRING );
if ( ! empty( $selected_zone ) ) {
$current_time = time();
switch ( $selected_zone ) {
case 'past':
$query->query_vars['meta_query'] = array(
array(
'key' => '_promo_end_date',
'value' => $current_time,
'compare' => '<',
),
);
break;
case 'current':
$query->query_vars['meta_query'] = array(
array(
'key' => '_promo_start_date',
'value' => $current_time,
'compare' => '<',
),
array(
'key' => '_promo_end_date',
'value' => $current_time,
'compare' => '>',
),
);
break;
case 'future':
$query->query_vars['meta_query'] = array(
array(
'key' => '_promo_start_date',
'value' => $current_time,
'compare' => '>',
),
);
break;
}
}
}
}
add_filter( 'parse_query', 'parse_query' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment