Выпадающее меню навигации, которое показывает последнее сообщение для каждой категории
Итак, я пытаюсь работать над своим меню навигации на своем веб-сайте wordpress. Я пытаюсь скопировать меню навигации с hongkiat.com(показано на картинке).
В навигационном меню Hongkiat вы увидите ПЯТЬ (5) родительских категорий (Design/dev, Technology, Inspiration, SOcial COmmerce and Deal). После того, как пользователь зависает в родительской категории, он покажет последние сообщения в разделе "Родительские категории".
В любом случае мне удалось закодировать раскрывающееся меню с родительской категорией, показывающей плюс его дочернюю категорию. Теперь дилемма заключается в том, как я могу отобразить последнее сообщение (не менее 3 сообщений) под родительской категорией, зависающее пользователем.
![введите описание изображения здесь]()
В любом случае, здесь мой код:
HTML/PHP
<ul>
<?php
global $post;
$myposts = get_posts('numberposts=3&offset=1');
foreach($myposts as $post) ;
$args = array(
'show_option_all' => '',
'hide_empty' => '0',
'orderby' => 'name',
'order' => 'ASC',
'style' => 'list',
'use_desc_for_title' => 1,
'child_of' => 0,
'hierarchical' => 1,
'title_li' => (''),
'show_option_none' => __( '' ),
'number' => null,
'echo' => 1,
'depth' => 2,
'current_category' => 0,
'pad_counts' => 0,
'taxonomy' => 'category',
'walker' => null
);
wp_list_categories( $args );
?>
</ul>
CSS
.navone {
display:inline-block;
height:35px;
vertical-align:middle;
margin:0px auto;
font-family: "Raleway",san-serif;
font-feature-settings: normal;
font-kerning: auto;
font-language-override: normal;
font-size: 12px;
font-size-adjust: none;
font-stretch: normal;
font-style: normal;
font-synthesis: weight style;
font-variant: normal;
font-weight: 600 !important;
letter-spacing: 0.03em;
text-transform:uppercase;
}
.navone ul {
margin:0;
padding:0;
}
.navone ul ul {
display: none;
}
.navone ul li:hover > ul {
display: block;
-webkit-transition: all .25s ease;
-moz-transition: all .25s ease;
-ms-transition: all .25s ease;
-o-transition: all .25s ease;
transition: all .25s ease;
}
.navone ul {
list-style: none;
position: relative;
display: inline-table;
}
.navone ul:after {
content: ""; clear: both; display: block;
}
.navone ul li {
float: left;
cursor:pointer;
padding:10px 20px;
}
.navone ul li:hover {
background:#000;
}
.navone ul li:hover a {
color: #fff;
}
.navone ul li a {
display: block;
color: #FFF;
text-decoration: none;
}
.navone ul li ul {
width:200px;
z-index:9;
}
.navone ul ul {
background: #000;
padding: 0;
position: absolute;
top:100%;
left:0;
}
.navone ul ul li {
float: none;
position: relative;
padding:5px 10px;
}
.navone ul ul li a {
color: #fff;
}
.navone ul ul li a:hover {
-webkit-transition: all .25s ease;
-moz-transition: all .25s ease;
-ms-transition: all .25s ease;
-o-transition: all .25s ease;
transition: all .25s ease;
}
.navone ul ul ul {
position: absolute; left: 100%; top:0;
}
.navone ul li ul li {
padding:8px 10px;
-webkit-transition: all .25s ease;
-moz-transition: all .25s ease;
-ms-transition: all .25s ease;
-o-transition: all .25s ease;
transition: all .25s ease;
}
.navone ul li ul li:hover {
border-left:5px solid #F52100;
padding-left:20px;
-webkit-transition: all .25s ease;
-moz-transition: all .25s ease;
-ms-transition: all .25s ease;
-o-transition: all .25s ease;
transition: all .25s ease;
}
.navtwo {
display:inline;
}
ЕСЛИ кто-нибудь может мне помочь или указать, чего я не вижу, потому что мой код не работает. У моего кода нет ошибок, но я не достигаю того, чего хочу достичь.
Может ли кто-нибудь протянуть руку помощи.
Ответы
Ответ 1
<ul>
<?php $args = array(
'type' => 'post',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'category',
'pad_counts' => false
);
$categories = get_categories( $args );
foreach($categories as $cat)
{
if ($cat->category_parent == 0) {
?>
<li>
<?php echo $cat->name; $cat_id = $cat->term_id;?>
<?php $post_args = array(
'post_type'=>'post',
'posts_per_page' => 3,
'cat' => $cat_id
);
$the_query = new WP_Query($post_args);
if($the_query->have_posts()): ?>
<ul>
<?php while($the_query->have_posts()): $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; wp_reset_query(); ?>
</li>
<?php } }?>
</ul>
Ответ 2
Вы можете попробовать следующее:
<ul>
<?php $args = array(
'type' => 'post',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'category',
'pad_counts' => false
);
$categories = get_categories( $args );
foreach($categories as $cat): ?>
<li>
<?php echo $cat->$name; $cat_id = $cat->$term_id;?>
<?php $post_args = array(
'post_type'=>'post',
'posts_per_page' => 3,
'cat' => $cat_id
);
$the_query = new WP_Query($post_args);
if($the_query->have_posts()): ?>
<ul>
<?php while($the_query->have_posts()): $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; wp_reset_query(); ?>
</li>
<?php endforeach; ?>
</ul>
Он не тестировался, но он должен работать.
Ответ 3
В приведенном выше коде вам не хватает нескольких вещей.
Попробуйте сделать это простым.
Шаг 1. Получите все родительские категории и дочерние категории под ними в массиве с именем $total_categories
Вы можете увидеть код ниже, чтобы получить массив для всех родительских категорий и дочерних категорий
<?php
$parent_args = array(
'type' => 'post',
'parent' => '0',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 0,
'hierarchical' => 1,
'taxonomy' => 'category',
'pad_counts' => false
);
$parent_categories = get_categories( $parent_args );
foreach ($parent_categories as $parent_category) {
$child_args = array(
'type' => 'post',
'parent' => $parent_category->term_id,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 0,
'hierarchical' => 1,
'taxonomy' => 'category',
'pad_counts' => false
);
$cats_arr = array();
$child_categories = get_categories( $child_args );
$cats_arr[] = $parent_category->term_id;
foreach ($child_categories as $child_category) {
$cats_arr[] = $child_category->term_id;
}
$total_categories[$parent_category->term_id] = $cats_arr;
}
?>
Выход был предоставлен для моего случая
Над массивом будет выглядеть, где 18 - это идентификатор родительской категории, а дочерние категории 19 и 20 плюс мы также включили идентификатор родительской категории ( 18) в массиве, а также индекс массива.
Array
(
[18] => Array
(
[0] => 18
[1] => 19
[2] => 20
)
[15] => Array
(
[0] => 15
[1] => 16
[2] => 17
)
[1] => Array
(
[0] => 1
)
)
Теперь просто перейдите массив $total_categories
, чтобы получить все родительские категории и верхние 3 сообщения под этими категориями
<ul>
<?php foreach($total_categories as $total_category_k=>$total_category_v): ?>
<li>
<a href=""><?php echo get_the_category_by_ID($total_category_k);?></a>
<?php $post_args = array(
'post_type'=>'post',
'posts_per_page' => 3,
'orderby'=>'ID',
'order'=>'DESC',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $total_category_v,
'operator' => 'IN'
),
),
);
$the_query = new WP_Query($post_args);
if($the_query->have_posts()): ?>
<ul>
<?php while($the_query->have_posts()): $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; wp_reset_query(); ?>
</li>
<?php endforeach; ?>
</ul>
Выход был предоставлен для моего случая
И он, наконец, даст вам желаемый HTML с требуемым контентом, как показано ниже:
<ul>
<li>
<a href="">menu</a>
</li>
<li>
<a href="">test</a>
</li>
<li>
<a href="">Uncategorized</a>
<ul>
<li>
<a href="#" onclick="location.href='http://localhost/wp/clark_atlanta_university/students-unlock-the-mysteries-of-the-brain-with-nih-scientists/'; return false;">Students unlock the mysteries of the brain with NIH scientists</a>
</li>
<li>
<a href="#" onclick="location.href='http://localhost/wp/clark_atlanta_university/contacts-better-than-permanent-lenses-for-babies-after-cataract-surgery/'; return false;">Contacts better than permanent lenses for babies after cataract surgery</a>
</li>
<li>
<a href="#" onclick="location.href='http://localhost/wp/clark_atlanta_university/nih-announces-recruitment-for-clinical-trial-to-test-new-tinnitus-treatment-device/'; return false;">NIH announces recruitment for clinical trial to test new tinnitus treatment device</a>
</li>
</ul>
</li>
</ul>
Недопустимый код:
'orderby'=>'ID',
'order'=>'DESC',
Чтобы получить 3 сообщений, вы должны будете получить сообщения в нисходящем закажите по ID и, конечно, posts_per_page получит только 3 записи
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $total_category_v,
'operator' => 'IN'
),
),
);
И для получения сообщений, связанных с категориями (будь то родительский или дочерний) поэтому мы передали массив, содержащий как родительский, так и дочерний Категории