[英]List WordPress categories and subcategories with posts
嘿,很棒的程序员们!
我有一个功能齐全的PHP代码段,其中列出了类别及其帖子,但现在有了子类别! 我想扩展当前脚本,但无所适从,我的PHP知识很基础,但我正在学习。
以下脚本的功能是:
列出要在类别中发布的链接
<div class="menu-main-menu-container"> <ul id="primary-menu" class="menu nav-menu" aria-expanded="false"> <?php $cat_args = array( 'taxonomy' => 'products-category', ); $categories = get_categories($cat_args); foreach ($categories as $category) { $cat_query = null; $args = array( 'order' => 'ASC', 'orderby' => 'title', 'posts_per_page' => -1, 'post_type' => 'products', 'taxonomy' => 'products-category', 'term' => $category->slug ); $cat_query = new WP_Query($args); ?> <?php if ($cat_query->have_posts()) { echo "<li class='page_item'>" . $category->name; echo "<ul class='custom-submenu'>"; while ($cat_query->have_posts()) { $cat_query->the_post(); ?> <li> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> </li> <?php } echo "</ul></li>"; } wp_reset_postdata(); } ?> </ul> </div>
我想要实现的是:
例如,我想将第一个菜单项“ Bars”更改为包括“ front bar”和“ back bar”(两个子类别),然后在其他子菜单中列出它们的帖子。
预先感谢您的协助和知识,希望我能提供足够的信息! :)
与一位朋友一起花了一些时间正确地创建了此文件,以后对任何想要搜索此文件的人,请参阅此处:
https://freshlondon.biz/wordpress-menu-from-categories-subcategories-and-posts/
我已经尽力了。
在这里,我仅根据类别创建菜单。 如果该类别没有子类别,则我只在子菜单下列出其自己的帖子详细信息,如果它具有子类别,则将该子类别列为一个子菜单,然后在该子类别下列出该子类别的帖子。
希望对您有所帮助,并且符合您的要求。
$category = get_categories();
foreach ($category as $value){
$cat_id = $value->term_id;
// Check if this category has a child category
if(!empty(category_has_children($cat_id))){
$subcategories = category_has_children($cat_id);?>
<ul class="parent_menu">
<?php echo $value->cat_name;
foreach($subcategories as $subcategory_data) {
?>
<li class="sub_menu">
<?php echo $subcategory_data->name;
// function to list all the post details
get_category_data_post($subcategory_data->term_id);
?>
</li><?php
}
?>
</ul>
<?php
} else{
// Category which don't have sub category
if($value->parent ==0) {
?>
<ul class="parent_menu">
<?php echo $value->cat_name;
get_category_data_post($value->term_id);
?>
</ul>
<?php
}
}?>
<?php
}
function category_has_children( $term_id = 0, $taxonomy = 'category' ) {
$children = get_categories( array(
'child_of' => $term_id,
'taxonomy' => $taxonomy,
'hide_empty' => false
) );
return ( $children );
}
function get_category_data_post($cat_id){
$args = array(
'category' => $cat_id
);
$posts = get_posts($args);
foreach ($posts as $val) {
?>
<ol class="sub_menu_2">
<a href="<?php echo get_post_permalink($val->ID); ?>"></a><?php echo $val->post_title; ?>
</ol>
<?php
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.