简体   繁体   中英

Wordpress category - list posts and subcategories

i've got problem with listing posts and subcategories in category page. What i need is:

Main category page headline

Subcategory 1

  • post 1
  • post 2
  • post 3

Subcategory 2

  • post 1
  • post 2
  • post 3

I working with custom post types, so it might be little bit harder. Thanks for help.

You can use following code with post_type = your desired type

$subcats = get_categories('child_of=' . $catID);
foreach($subcats as $subcat) {
    echo '<h2>' . $subcat->cat_name . '</h2>';
    echo '<ul>';
    $args = array('post_type'    => 'post','category'=>$subcat->cat_ID);
    $subcat_posts = get_posts($args);
    foreach($subcat_posts as $subcat_post) {
        $postID = $subcat_post->ID;
        echo '<li>';
        echo '<a href="' . get_permalink($postID) . '">';
        echo get_the_title($postID);
        echo '</a></li>';
    }
    echo '</ul>';
}

Finally i figure out like this:

<?php 

$parentCatName = single_cat_title('',false);
$catID = get_cat_ID($parentCatName);
$parentCatID = get_cat_ID($parentCatName);
$categories = get_categories( 'child_of='.$parentCatID ); 
$subcats = get_categories('child_of=' . $catID);

  ?> 
 <?php  foreach ($categories as $cat) { ?>
    <div class="genre_subcat">
        <?php query_posts("cat=$cat->cat_ID&showposts=-1&order=ASC&orderby=name&post_type=armatury-voda"); ?>
        <h2><?php single_cat_title(); ?></h2>
        <small><?php echo category_description($cat->cat_ID); ?></small>
        <?php while (have_posts()) : the_post(); ?>
            <div class="post hentry"> 
      <?php $url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail'); ?>
    <img src="<?php echo $url[0]; ?>" alt="" width="150" /> 
                <h3><?php the_title(); ?></h3>
                <?php the_content(); ?>
        <?php
$myname = get_post_meta($post->ID, 'kestazeni', true);
if ( $myname ) {  ?>

        <div class="dont"><a href="<?php echo do_shortcode ('[field "kestazeni"]'); ?>">Stáhnout PDF</a></div>

 <?php
}
else {
echo '';
}
?>

            </div>
        <?php endwhile; ?>
    </div>    
      <?php }?> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM