![](/img/trans.png)
[英]MYSQL 8 + : Query to find the products under categories , when category is in hierarchy and product is attached to leaf category node
[英]Wordpress - listing a hierarchy of categories with posts under each category
在wordpress中,以下功能將回顯類別列表,並在每個類別名稱下方顯示與每個類別關聯的帖子。
除產生平面結構的事實外,此方法均工作正常。 一些類別是子類別,其他類別,我希望能夠輸出具有與此結構相匹配的結構的列表(有點像站點地圖)
有誰能夠幫助我找出如何修改此代碼來實現這一目標?
function posts_by_category() {
//get all categories then display all posts in each term
$taxonomy = 'category';
$param_type = 'category__in';
$term_args=array(
'orderby' => 'name',
'order' => 'ASC'
);
$terms = get_terms($taxonomy,$term_args);
if ($terms) {
foreach( $terms as $term ) {
$args=array(
"$param_type" => array($term->term_id),
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { ?>
<div class="category section">
<h3><?php echo ''.$term->name;?></h3>
<ul>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
</div>
<?php
}
}
}
wp_reset_query(); // Restore global post data stomped by the_post().
}
這是我前幾天發現的帶有Post Titles的Hierarchical Category List的代碼片段,應該可以解決問題。
<?php
/*****************************************************************
*
* alchymyth 2011
* a hierarchical list of all categories, with linked post titles
*
******************************************************************/
// http://codex.wordpress.org/Function_Reference/get_categories
foreach( get_categories('hide_empty=0') as $cat ) :
if( !$cat->parent ) {
echo '<ul><li><strong>' . $cat->name . '</strong></li>';
process_cat_tree( $cat->term_id );
}
endforeach;
wp_reset_query(); //to reset all trouble done to the original query
//
function process_cat_tree( $cat ) {
$args = array('category__in' => array( $cat ), 'numberposts' => -1);
$cat_posts = get_posts( $args );
if( $cat_posts ) :
foreach( $cat_posts as $post ) :
echo '<li>';
echo '<a href="' . get_permalink( $post->ID ) . '">' . $post->post_title . '</a>';
echo '</li>';
endforeach;
endif;
$next = get_categories('hide_empty=0&parent=' . $cat);
if( $next ) :
foreach( $next as $cat ) :
echo '<ul><li><strong>' . $cat->name . '</strong></li>';
process_cat_tree( $cat->term_id );
endforeach;
endif;
echo '</ul>';
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.