Created
February 23, 2019 12:01
-
-
Save tomaskavalek/35d826e4b2820579e12b0d78a14c6cd5 to your computer and use it in GitHub Desktop.
WooCommerce Admin Custom Products Filtering
This file contains 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
<?php | |
/** | |
* Return (render :-D) HTML Select > Option for filtering | |
* | |
* @param string $post_type | |
* @return void | |
*/ | |
function webona_custom_product_filters(string $post_type): void | |
{ | |
if ($post_type !== 'product') { | |
return; | |
} | |
$options = [ | |
'with-images' => __('Produkty s obrázky', 'webona'), | |
'no-images' => __('Produkty bez obrázků', 'webona'), | |
]; | |
$selected = isset($_GET['webona_custom_product_filter']) ? $_GET['webona_custom_product_filter'] : null; | |
$o = ''; | |
$o .= '<select name="webona_custom_product_filter">'; | |
$o .= ' <option value>Zobrazit vše</option>'; | |
foreach ($options as $value => $option) { | |
$is_selected = ($value === $selected) ? 'selected="selected"' : ''; | |
$o .= ' <option value="' . $value . '" ' . $is_selected . '>' . $option . '</option>'; | |
} | |
$o .= '</select>'; | |
echo $o; | |
} | |
add_action('restrict_manage_posts', 'webona_custom_product_filters'); | |
/** | |
* Applying filter, if exists | |
* | |
* @param WP_Query $query | |
* @return void | |
*/ | |
function apply_webona_custom_product_filters(\WP_Query $query): void | |
{ | |
global $pagenow; | |
if ( | |
$query->is_admin && | |
($pagenow == 'edit.php') && | |
isset($_GET['webona_custom_product_filter']) && | |
($_GET['webona_custom_product_filter'] !== '') && | |
($_GET['post_type'] == 'product') | |
) { | |
$filter = $_GET['webona_custom_product_filter']; | |
switch ($filter) { | |
case 'no-images': | |
$meta_key_query = array( | |
array( | |
'key' => '_thumbnail_id', | |
'compare' => 'NOT EXISTS', | |
) | |
); | |
$query->set('meta_query', $meta_key_query); | |
break; | |
case 'with-images': | |
$meta_key_query = array( | |
array( | |
'key' => '_thumbnail_id', | |
'compare' => 'EXISTS', | |
) | |
); | |
$query->set('meta_query', $meta_key_query); | |
break; | |
default: | |
break; | |
} | |
} | |
return; | |
} | |
add_action('pre_get_posts', 'apply_webona_custom_product_filters'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment