Skip to content

Instantly share code, notes, and snippets.

@aguilar1181
Last active June 13, 2019 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aguilar1181/9311122b405bbe6f7ff4 to your computer and use it in GitHub Desktop.
Save aguilar1181/9311122b405bbe6f7ff4 to your computer and use it in GitHub Desktop.
Woocommerce Custom Admin Filter Dropdown
<?php
//Add custom filter dropdown to admin for CPT
function wpse45436_admin_posts_filter_restrict_manage_posts(){
$type = 'post';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
//only add filter to post type you want
if ('product' == $type){
//change this to the list of values you want to show
//in 'label' => 'value' format
$values = array(
'Yes' => 'Yes',
);
?>
<select name="ADMIN_FILTER_FIELD_VALUE">
<option value=""><?php _e('Filter by Sold ', 'wose45436'); ?></option>
<?php
$current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
foreach ($values as $label => $value) {
printf
(
'<option value="%s"%s>%s</option>',
$value,
$value == $current_v? ' selected="selected"':'',
$label
);
}
?>
</select>
<?php
}
}
add_action( 'restrict_manage_posts', 'wpse45436_admin_posts_filter_restrict_manage_posts', 50);
//Bring the results from the filter dropdown
function wpse45436_posts_filter( $query ){
global $pagenow;
$type = 'post';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
if ( 'product' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '') {
$query->query_vars['meta_key'] = 'sold'; //change this for your custom field name
$query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
}
}
add_filter( 'parse_query', 'wpse45436_posts_filter' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment