Skip to content

Instantly share code, notes, and snippets.

@corsonr
Created February 21, 2014 10:47
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 corsonr/9132329 to your computer and use it in GitHub Desktop.
Save corsonr/9132329 to your computer and use it in GitHub Desktop.
WooCommerce : search by sku in admin (temporary fix)
<?php
/**
* Search by SKU or ID for products. Adapted from code by BenIrvin (Admin Search by ID)
*
* @access public
* @param mixed $wp
* @return void
*/
function woocommerce_admin_product_search( $wp ) {
global $pagenow, $wpdb;
if( 'edit.php' != $pagenow ) return;
if( !isset( $wp->query_vars['s'] ) ) return;
if ($wp->query_vars['post_type']!='product') return;
if( '#' == substr( $wp->query_vars['s'], 0, 1 ) ) :
$id = absint( substr( $wp->query_vars['s'], 1 ) );
if( !$id ) return;
unset( $wp->query_vars['s'] );
$wp->query_vars['p'] = $id;
elseif( 'SKU:' == strtoupper( substr( $wp->query_vars['s'], 0, 4 ) ) ) :
$sku = trim( substr( $wp->query_vars['s'], 4 ) );
if( !$sku ) return;
$ids = $wpdb->get_col( 'SELECT post_id FROM ' . $wpdb->postmeta . ' WHERE meta_key="_sku" AND meta_value LIKE "%' . $sku . '%";' );
if ( ! $ids ) return;
unset( $wp->query_vars['s'] );
$wp->query_vars['post__in'] = $ids;
$wp->query_vars['sku'] = $sku;
endif;
}
/**
* Label for the search by ID/SKU feature
*
* @access public
* @param mixed $query
* @return void
*/
function woocommerce_admin_product_search_label($query) {
global $pagenow, $typenow, $wp;
if ( 'edit.php' != $pagenow ) return $query;
if ( $typenow!='product' ) return $query;
$s = get_query_var( 's' );
if ($s) return $query;
$sku = get_query_var( 'sku' );
if($sku) {
$post_type = get_post_type_object($wp->query_vars['post_type']);
return sprintf(__( '[%s with SKU of %s]', 'woocommerce' ), $post_type->labels->singular_name, $sku);
}
$p = get_query_var( 'p' );
if ($p) {
$post_type = get_post_type_object($wp->query_vars['post_type']);
return sprintf(__( '[%s with ID of %d]', 'woocommerce' ), $post_type->labels->singular_name, $p);
}
return $query;
}
if ( is_admin() ) {
add_action( 'parse_request', 'woocommerce_admin_product_search' );
add_filter( 'get_search_query', 'woocommerce_admin_product_search_label' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment