Last active
October 13, 2015 17:47
-
-
Save wokamoto/4232885 to your computer and use it in GitHub Desktop.
[WordPress] ダッシュボードの投稿一覧にカスタムフィールドの値での絞り込み検索を追加する
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 | |
add_filter('query_vars', function($vars){ | |
array_push($vars, 'my_meta_key'); | |
return $vars; | |
}); | |
add_action('restrict_manage_posts', function(){ | |
printf( | |
'<input type="text" id="%1$s" name="%1$s" value="%2$s" />', | |
'my_meta_key', | |
esc_attr(get_query_var('my_meta_key')) | |
); | |
}); | |
add_filter('posts_where', function( $where ) { | |
global $wpdb; | |
if ( !is_admin() ) | |
return $where; | |
$value = get_query_var('my_meta_key'); | |
if ( !empty($value) ) { | |
$where .= $wpdb->prepare(" | |
AND EXISTS ( | |
SELECT 'x' | |
FROM {$wpdb->postmeta} as m | |
WHERE m.post_id = {$wpdb->posts}.ID | |
AND m.meta_key = 'my_meta_key' | |
AND m.meta_value like %s | |
)", | |
"%{$value}%" | |
); | |
} | |
return $where; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment