管理画面の固定ページ一覧にカスタムフィールドの検索条件を追加
WordPress 管理画面 固定ページ一覧 カスタムフィールド 検索条件
クエリパラメータ追加
◆ 条件
クエリパラメータ:param_check
function add_query_vars($vars){
$vars[] = 'param_check';
return $vars;
}
add_filter('query_vars', 'add_query_vars');
検索用ドロップダウン追加
◆ 条件
ドロップダウン項目
- 値:空白、テキスト:すべてのページ
- 値:1、テキスト:チェックページ
function custom_post_restrict_manage_page() {
global $post_type;
if ( $post_type != 'page' ) return;
$selected = get_query_var('param_check');
$options = '';
$options .= sprintf(
'<option value="%s" %s>%s</option>',
'1',
($selected=='1') ? 'selected="selected"' : '',
'チェックページ'
);
$select_html = '<select name="param_check"><option value="">すべてのページ</option>%s</select>';
printf($select_html , $options);
}
add_action('restrict_manage_posts', 'custom_post_restrict_manage_page');
クエリ編集
◆ 条件
meta_key = page_check
function custom_post_page_where($where){
global $wpdb;
if ( !is_admin() ) {
return $where;
}
$param_check= get_query_var('param_check');
if(empty ($param_check)){
return $where;
}
$where .= $wpdb->prepare("AND EXISTS (SELECT * FROM {$wpdb->postmeta} as m
WHERE m.post_id = {$wpdb->posts}.ID AND m.meta_key='page_check'
AND m.meta_value is not null and m.meta_value == %s)",
$param_check);
return $where;
}
add_filter('posts_where', 'custom_post_page_where');
または
function query_pre_get_posts( $query ) {
global $wpdb;
if ( !is_admin() ) {
return;
}
$param_check= get_query_var('param_check');
if(empty ($param_check)){
return;
}
$meta_query = $query->get('meta_query');
if(!$meta_query || !is_array($meta_query)) {
$meta_query = array();
}
$meta_query['relation'] = 'and';
$meta_query[] = array(
'key' => 'page_check',
'value' => $param_check,
'compare' => '=',
);
$query->set('meta_query', $meta_query);
}
add_action('pre_get_posts', 'query_pre_get_posts', 10, 1);