WordPress管理画面でACFの日付データを拾って、月別フィルターをかけたい

study_chinese 仕事

数千件のデータがあって、そのデータの中にyyyy/mm/ddという形のメタデータがある。

過去のデータが削除しやすいように月別に絞り込みする機能がほしいという要望でした。

■カスタムクエリの追加
■開始日カスタムフィールドの年月ドロップダウンを追加
■月内のレッスンをフィルタするよう追加

add_filter( 'query_vars', 'goto_calendar_register_query_vars' );
function goto_calendar_register_query_vars( $qvars ) {

//Add these query variables
$qvars[] = 'custom_month';
return $qvars;

}

function goto_calendar_get_months(){
global $wpdb;
$months = wp_cache_get( 'goto_calendar_get_months' );
if ( false === $months ) {
$query = "SELECT YEAR( meta_value ) AS `year`, MONTH( meta_value ) AS `month`, count( post_id ) as posts
FROM $wpdb->postmeta
WHERE meta_key = 'lesson_date'
AND post_id IN ( SELECT ID FROM $wpdb->posts
WHERE post_type = 'trial_lessons'
AND post_status != 'trash' )
GROUP BY YEAR( meta_value ), MONTH( meta_value ) ORDER BY meta_value DESC";
$months = $wpdb->get_results($query);
wp_cache_set( 'goto_calendar_get_months', $months );
}
return $months;
}

add_action( 'restrict_manage_posts', 'goto_calendar_restrict_posts_by_metavalue' );

function goto_calendar_restrict_posts_by_metavalue() {

global $typenow;
$months = goto_calendar_get_months();

if ($typenow == 'trial_lessons') {

$selected = get_query_var('custom_month');
$output = '

if ( ! empty( $months ) ) {

foreach ( $months as $month ) {
$value = esc_attr( $month->year . '/' . $month->month );
$month_dt = new DateTime( $month->year . '-' . $month->month . '-01' );
$output .= '' . $month_dt->format( 'Y年m月' ) . '';
}

}
$output .= '' . "\n";

echo $output;

}

}

add_action( 'pre_get_posts', 'goto_calendar_pre_get_posts' );
function goto_calendar_pre_get_posts( $query ) {

//Only alter query if custom variable is set.
$month_str = $query->get( 'custom_month' );
if( !empty( $month_str ) ){

$meta_query = $query->get( 'meta_query' );
if( empty( $meta_query ) )
$meta_query = array();

$month = new DateTime($month_str.'/01');

$meta_query[] = array(
'key' => 'lesson_date',
'value' => array( $month->format( 'Ymd' ), $month->format( 'Ymt' ) ),
'compare' => 'BETWEEN',
);
$query->set( 'meta_query', $meta_query );

}
}

コメント

タイトルとURLをコピーしました