0

有人可以帮助我使用下面的代码。它工作正常,但我只是不想为每个类别编写一段代码。所以基本上,我想让父类别显示一次,以便在子类别中列出它们下面的所有帖子。

我知道我需要一个 for 循环,但不确定它是如何编写的。

<h4>2012</h4>
    <ul class="news-coverage">
     <?php $cat_id = get_cat_ID('2012-media');
    $args=array(
      'cat' => $cat_id,
      'post_type' => 'press',
      'post_status' => 'publish',
      'posts_per_page' => 100,
      'caller_get_posts'=> 1,
      'exclude' => 28,
      'offset' => 9

    );
    $new = new WP_Query($args);
     $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
    echo '<li><i class="foundicon-page"></i><strong>';
        the_title();echo '</strong><span>';
        the_date(); echo '</span>';
        the_content();
    echo '</li>';
    endwhile; ?>

    </ul>

    <h4>2011</h4>   
                  <hr>
    <ul class="news-coverage">
     <?php $cat_id = get_cat_ID('2011-media');
    $args=array(
      'cat' => $cat_id,
      'post_type' => 'press',
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'caller_get_posts'=> 1,
      'exclude' => 28
    );
    $new = new WP_Query($args);
     $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
    echo '<li><i class="foundicon-page"></i><strong>';
        the_title();echo '</strong><span>';
        the_date(); echo '</span>';
        the_content();
    echo '</li>';
    endwhile; ?>

    </ul>
4

1 回答 1

0

你去:(未测试)

<?php
/* add category prefixes here */
$years = array( '2011', '2012' );

$output = '';

/* iterate over categories */
foreach( $years as $year )
{
    /* add the heading */
    $output .= sprintf( '<h4>%s</h4>', $year );

    /* setup current query/loop */
    $args = array(
        'cat' => get_cat_ID( $year . '-media' ),
        'post_type' => 'press',
        'post_status' => 'publish',
        'posts_per_page' => 100,
        'caller_get_posts' => 1,
        'exclude' => 28,
        'offset' => 9
    );
    $loop = new WP_Query( $args );

    /* iterate over articles */
    $listItems = '';
    while( $loop->have_posts() )
    {
        $loop->the_post();
        $listItems .= sprintf( '<li><i class="foundicon-page"></i><strong>%s</strong><span>%s</span>%s</li>',
            get_the_title(),
            get_the_date(),
            get_the_content()
        );
    }

    $output .= sprintf( '<ul class="news-coverage">%s</ul>', $listItems );
}

echo $output;
?>
于 2012-09-26T23:55:10.220 回答