回答編集履歴

4

コードの各箇所にコメント追加

2021/06/19 08:39

投稿

m.ts10806
m.ts10806

スコア80850

test CHANGED
@@ -74,23 +74,35 @@
74
74
 
75
75
  $selected_check = false;
76
76
 
77
+
78
+
79
+ //3番目が年、4番目が月。
80
+
81
+ //どちらもない場合は /news/ だけと判定できるのでそもそもselectedの判定をしない
82
+
77
83
  if(isset($urilist[3]) && isset($urilist[4])){
78
84
 
79
85
  $selected_check = true;
80
86
 
81
87
  }
82
88
 
89
+
90
+
91
+ // $archive_list をループ
92
+
83
93
  foreach ($archive_list as $year_month => $archive) :
84
94
 
85
- $selected = '';
95
+ $selected = ''; //初期化(合致しないときにはselectedを出さない)
86
96
 
87
97
  if($selected_check && $year_month === ($urilist[3].'/'.$urilist[4])){
98
+
99
+ //$year_monthがURLにあるものと合致していればselected
88
100
 
89
101
  $selected = ' selected';
90
102
 
91
103
  }
92
104
 
93
- $year_month_arr = explode('/', $year_month);
105
+ $year_month_arr = explode('/', $year_month); //これは元のコードです。
94
106
 
95
107
  ?>
96
108
 

3

短縮構文修正

2021/06/19 08:39

投稿

m.ts10806
m.ts10806

スコア80850

test CHANGED
@@ -98,7 +98,7 @@
98
98
 
99
99
 
100
100
 
101
- <option value="<?php echo esc_url(home_url('/news/date/' . $year_month . '/' . '?' . $taxonomy_slug . '=' . $term)) ?>"<?php=$selected ?>>
101
+ <option value="<?php echo esc_url(home_url('/news/date/' . $year_month . '/' . '?' . $taxonomy_slug . '=' . $term)) ?>"<?=$selected ?>>
102
102
 
103
103
 
104
104
 

2

URIのチェックを外だし。

2021/06/19 06:00

投稿

m.ts10806
m.ts10806

スコア80850

test CHANGED
@@ -72,11 +72,19 @@
72
72
 
73
73
  $urilist = explode("/",$_SERVER['REQUEST_URI']);
74
74
 
75
+ $selected_check = false;
76
+
77
+ if(isset($urilist[3]) && isset($urilist[4])){
78
+
79
+ $selected_check = true;
80
+
81
+ }
82
+
75
83
  foreach ($archive_list as $year_month => $archive) :
76
84
 
77
85
  $selected = '';
78
86
 
79
- if(isset($urilist[3]) && isset($urilist[4]) && $year_month === ($urilist[3].'/'.$urilist[4])){
87
+ if($selected_check && $year_month === ($urilist[3].'/'.$urilist[4])){
80
88
 
81
89
  $selected = ' selected';
82
90
 

1

edit

2021/06/19 05:26

投稿

m.ts10806
m.ts10806

スコア80850

test CHANGED
@@ -55,3 +55,45 @@
55
55
 
56
56
 
57
57
  そこでその配列の番号を指定して年月を取得し同じならselectedをつけるとかで対応できると思います([isset()](https://www.php.net/manual/ja/function.isset.php)とかで確認して存在しなければ「全て」ですね)
58
+
59
+
60
+
61
+ ---
62
+
63
+
64
+
65
+ WordPress環境手元にないので未検証ですが、このような形で。
66
+
67
+ ```php
68
+
69
+
70
+
71
+ <?php
72
+
73
+ $urilist = explode("/",$_SERVER['REQUEST_URI']);
74
+
75
+ foreach ($archive_list as $year_month => $archive) :
76
+
77
+ $selected = '';
78
+
79
+ if(isset($urilist[3]) && isset($urilist[4]) && $year_month === ($urilist[3].'/'.$urilist[4])){
80
+
81
+ $selected = ' selected';
82
+
83
+ }
84
+
85
+ $year_month_arr = explode('/', $year_month);
86
+
87
+ ?>
88
+
89
+
90
+
91
+
92
+
93
+ <option value="<?php echo esc_url(home_url('/news/date/' . $year_month . '/' . '?' . $taxonomy_slug . '=' . $term)) ?>"<?php=$selected ?>>
94
+
95
+
96
+
97
+
98
+
99
+ ```