Выберите & вариант, добавив индекс по алфавиту в php
Я работаю над сайтом с WordPress. Я включил меню выбора типа с именем и ссылками моих дочерних страниц одной родительской страницы. все отлично работает, мои страницы отсортированы по алфавиту ASC:
Bali
Bruxelles
Chicago
Edinburgh
Geneve
Los Angeles
Lyon
Miami
Paris
San Diego
San Francisco
Vancouver
Washington
Zurich
вот мой код:
<div class="styled-select">
<?php
if(!$post->post_parent){
$children = get_pages(array(
'child_of' => $post->ID,
'post_type' => 'page',
'post_status' => 'publish',
'sort_order' => 'ASC',
'sort_column' => 'post_title',
));
}else{
$children = get_pages(array(
'child_of' => $post->post_parent,
'post_type' => 'page',
'post_status' => 'publish',
'sort_order' => 'ASC',
'sort_column' => 'post_title',
));
}
if ($children) {
echo '<select name="" onchange="location = this.options[this.selectedIndex].value;">';
echo '<option>'. 'A - Z' .'</option>';
foreach($children as $child){
//print_r($child);
$permalink = get_permalink($child->ID);
echo '<option value="'.$permalink.'">'.$child->post_title.'</option>';
}
echo '</select>';
} ?>
</div>
Я хотел знать, возможно ли автоматически добавить алфавитный указатель (ширина в предположении) в моем меню, например так. добавьте "A" перед всеми страницами, начинающимися с A (когда есть страницы, начинающиеся с A...), добавьте "B" перед всеми страницами, начинающимися с B, и так далее... Что-то, что должно выглядеть так:
A
B
Bali
Bruxelles
C
Chicago
D
E
F
Edinburgh
G
Geneve
H
I
J
K
L
Los Angeles
Lyon
M
Miami
N
O
P
Paris
Q
R
S
San Diego
San Francisco
T
U
V
Vancouver
W
Washington
X
Y
Z
Zurich
Если кто-нибудь знает, кто я могу сделать это было бы очень признателен! большое спасибо
Mattieu
2 ответа
Использовать следующим образом (только для демонстрации):
function getInitials($name){
//split name using spaces
$words=explode(" ",$name);
$inits='';
//loop through array extracting initial letters
foreach($words as $word){
$inits.=strtoupper(substr($word,0,1));
}
return $inits;
}
$currval = "";
foreach($children as $child){
//print_r($child);
$permalink = get_permalink($child->ID);
$initial = getInitials($child->post_title);
if($initial!='' && $currval != $initial) {
$currval = $initial;
echo '<optgroup>'.$initial.'</option>';
}
echo '<option value="'.$permalink.'">'.$child->post_title.'</option>';
}
Не проверено, хотя.. пожалуйста, проверьте и вернитесь, если вы столкнулись с какой-либо проблемой
В случае, если вам нужно показать все алфавиты, я могу дать вам идею сделать это
function getInitials($name){
//split name using spaces
$words=explode(" ",$name);
$inits='';
//loop through array extracting initial letters
foreach($words as $word){
$inits.=strtoupper(substr($word,0,1));
}
return $inits;
}
$currval = "";
$alp = array('A'...'Z')
foreach($alp as $abc) {
foreach($children as $child){
//print_r($child);
$permalink = get_permalink($child->ID);
$initial = getInitials($child->post_title);
if($initial!='' && $currval != $initial && $initial == $abc) {
$currval = $initial;
echo '<optgroup>'.$initial.'</option>';
}
echo '<option value="'.$permalink.'">'.$child->post_title.'</option>';
}
}
Здравствуйте, я снова отредактировал код в соответствии с вашими потребностями.
пожалуйста, проверьте
<?php
function getInitials($name){
//split name using spaces
$words=explode(" ",$name);
$inits='';
//loop through array extracting initial letters
foreach($words as $word){
$inits = strtoupper(substr($word,0,1));
break;
}
return $inits;
}
$currval = "";
$alp = array('A','B','C','D','E','Y','S','Z');
//$children = array('Asin','Bali','Bruxelles','Chicago','Denmark','Edinburgh','Flag','San Francisco');
?>
<select name="test">
<?php
foreach($alp as $key => $abc) {
$showinOpt = false;
foreach($children as $child) {
$permalink = get_permalink($child->ID);
$initial = getInitials($child->post_title);
if($initial == $abc) {
if($currval != $initial) {
$currval = $initial;
echo '<optgroup label="'.$initial.'">'.$initial.'</optgroup>';
$showinOpt = true;
}
echo '<option value="'.$permalink.'">'.$child->post_title.'</option>';
}
}
if(!$showinOpt) {
echo '<optgroup label="'.$abc.'">'.$abc.'</optgroup>';
}
}
?>
</select>
Просто добавьте это после получения массива $children.