Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[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
You can’t perform that action at this time.