Skip to content

Instantly share code, notes, and snippets.

@wokamoto
Last active October 13, 2015 17:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wokamoto/4232885 to your computer and use it in GitHub Desktop.
Save wokamoto/4232885 to your computer and use it in GitHub Desktop.
[WordPress] ダッシュボードの投稿一覧にカスタムフィールドの値での絞り込み検索を追加する
<?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