Skip to content

Instantly share code, notes, and snippets.

@devudit
Created May 24, 2016 13:19
Show Gist options
  • Save devudit/dc37d5f170f2043e4a6de837539a29eb to your computer and use it in GitHub Desktop.
Save devudit/dc37d5f170f2043e4a6de837539a29eb to your computer and use it in GitHub Desktop.
Custom Filter On Post Listing
<?php
/**
*
* @wordpress-plugin
* Plugin Name: Custom Post Filter
* Plugin URI: http://uditrawat.com
* Description: Custom Post Filter For Posts
* Version: 1.3
* Author: Udit Rawat
* Author URI: http://uditrawat.com
* Text Domain: fws
*/
class CustomPostFilter
{
/**
* Instance of this class.
*
* @since 1.0.0
*
* @var object
*/
protected static $instance = null;
/**
* Return an instance of this class.
*
* @since 1.0.0
*
* @return object A single instance of this class.
*/
public static function get_instance()
{
// If the single instance hasn't been set, set it now.
if (null == self::$instance) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Class constructor
*
* @since 1.0.0
*/
private function __construct()
{
// Add filter dropdown to admin view
add_action('restrict_manage_posts', [$this, 'custom_filter']);
// Alter query
add_action('pre_get_posts', [$this, 'process_custom_filter']);
}
/**
* @param null
* @return null
*/
function custom_filter()
{
global $typenow;
$posttype = 'post';
//only add filter to post type you want
if ('post' == $typenow) {
$current_filter = isset($_GET['author_id']) ? $_GET['author_id'] : '';
$args = array(
'orderby' => 'name',
'order' => 'ASC',
'show_fullname' => true,
'echo' => false,
);
$filter = get_users();
$select = '<select name="author_id">';
$select .= '<option value="">Select Author</option>';
foreach ($filter as $value => $label) {
$select .= sprintf(
'<option value="%s" %s >%s</option>',
$label->ID,
$value == $current_filter ? ' selected="selected"' : '',
$label->display_name
);
}
$select .= "</select>";
echo $select;
}
}
/**
* @param $query
* @return null
*/
function process_custom_filter($query){
global $post_type, $pagenow;
if ($pagenow == 'edit.php' && $post_type == 'post') {
if (isset($_GET['author_id']) && $_GET['author_id'] != '') {
$query->query_vars['author'] = $_GET['author_id'];
}
}
}
}
if(class_exists('CustomPostFilter'))
add_action( 'plugins_loaded', array( 'CustomPostFilter', 'get_instance' ) );
/*
You can also add meta query like below
$query->query_vars['meta_query'][] = [
'key' => 'cause_category',
'value' => '"' . $_GET['cause_category'] . '"',
'compare' => 'LIKE'
];
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment