ACFの日付から年別アーカイブリストを表示するさいに値が無い(空)場合、表示が変になってしまい困っていて
foreachで回す際に空のデータを排除するれば良いのかなと思うんですがどうすればいいのか分かりません。
<?php function my_get_year_archives( $args = '' ) { global $wpdb, $wp_locale; $defaults = array( 'date_field' => 'date', 'format' => 'html', 'echo' => true, 'limit' => '', 'before' => '', 'after' => '', 'show_post_count' => false, ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); if ( '' != $limit ) { $limit = absint( $limit ); $limit = ' LIMIT '.$limit; } $field = 'm.meta_value'; $select = "SELECT SUBSTRING($field,1,4) AS `year`, count(p.ID) AS posts"; $where = "WHERE p.post_type = 'post' AND p.post_status = 'publish'"; $where .= $wpdb->prepare( ' AND m.meta_key = %s', $date_field ); $join = " INNER JOIN $wpdb->postmeta AS m ON m.post_id = p.ID"; $where = apply_filters( 'getarchives_where', $where, $r ); $join = apply_filters( 'getarchives_join' , $join , $r ); $output = ''; $query = "$select FROM $wpdb->posts AS p $join $where GROUP BY SUBSTRING($field,1,4) ORDER BY $field DESC $limit"; $key = md5( $query ); $cache = wp_cache_get( 'my_get_year_archives' , 'general' ); if ( !isset( $cache[ $key ] ) ) { $arcresults = $wpdb->get_results( $query ); $cache[ $key ] = $arcresults; wp_cache_set( 'my_get_year_archives', $cache, 'general' ); } else { $arcresults = $cache[ $key ]; } if ( $arcresults ) { $defAfter = (empty($_SERVER['HTTPS']) ? 'http://' : 'https://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; $After = preg_replace('/[^0-9]/', '', $defAfter); foreach ( (array) $arcresults as $arcresult ) { $After = substr($defAfter, 29, 4); // URLから年4桁を抜き出す $Years = $arcresult->year; $Cnt = $arcresult->posts; $selected = $Years === $After ? ' selected' : ''; $url = add_query_arg( array( 'meta_key' => $date_field ), get_year_link( $arcresult->year ) ); $text = sprintf( '%d', $arcresult->year ).'年'; $output .= '<option value="'.$url.'"'.$selected.'>'.$text.' ('.$Cnt.')</option>'; } } if ( $echo ) echo $output; else return $output; } add_action( 'init', 'my_init' ); function my_init() { global $wp; $wp->add_query_var( 'meta_key' ); } add_action( 'pre_get_posts', 'my_pre_get_posts' ); function my_pre_get_posts( $query ) { if ( $query->is_year ) { $meta_query = array( array( 'key' => $query->get( 'meta_key' ), 'value' => $query->get( 'year' ), 'compare' => 'LIKE' ), ); $query->set( 'meta_query' , $meta_query ); $query->set( 'year' , '' ); $query->set( 'date' , '' ); $query->set( 'meta_key' , '' ); } } ?>
<?php my_get_year_archives( array( 'date_field' => 'mydate', ) ); ?>
どうすれば良いのかのでしょうか?
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。