【问题标题】:Wordpress - How to show only years and months that have posts in archive listWordpress - 如何仅显示存档列表中有帖子的年份和月份
【发布时间】:2015-02-19 22:13:26
【问题描述】:

我有一个按年和月显示帖子的存档列表。但它显示了没有帖子的年份和月份。我怎样才能只显示实际有帖子的月份和年份?谢谢。

<?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM    $wpdb->posts WHERE  post_status = 'publish' ORDER BY post_date DESC"); ?>

<?php foreach($years as $year) : ?>
<span class="anni"><?php echo $year; ?></span>
        <ul style="list-style-type:none;"> 
        <?php $months = $wpdb->get_col("SELECT DISTINCT MONTH(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND YEAR(post_date) = '".$year."' ORDER BY post_date DESC"); ?>

        <?php foreach($months as $month) : ?>

        <li><h3 class="mesi"><?php echo date( 'F', mktime(0, 0, 0, $month) );?></h3>
            <ul> 

            <?php  $theids = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND MONTH(post_date)= '".$month."' AND YEAR(post_date) = '".$year."' ORDER BY post_date DESC"); ?>

                <?php foreach ($theids as $theid): ?>
            <li class="archivelist">


                    <div style="width:150px;height:170px;float:left;margin:10px;">
            <a href="<?php bloginfo('url'); ?>?p=<?php echo $theid->ID; ?>">

            <?php if (strlen($theid->post_title) > 15) :?>
                <?php echo substr($theid->post_title, 0, 15) . '...'; ?>
            <?php else : ?>
                <?php echo $theid->post_title; ?>
            <?php endif; ?>

            <?php if (has_post_thumbnail($theid->ID) ) : ?>
                    <?php echo get_the_post_thumbnail( $theid->ID, 'thumbnail' ); ?>
            <?php else : ?>
                <?php echo '<img style="width:150px;" src="wp-content/themes/twentythirteen-child/images/noimg.jpg"/>' ;?>
            <?php endif; ?>
                </a>

            </div>
            </li>
                <?php endforeach; ?>

            </ul>   <br style="clear:left;"> 

        </li>

        <?php endforeach; ?>

        </ul>


    <?php endforeach; ?>

【问题讨论】:

    标签: php wordpress archive


    【解决方案1】:

    显然,几个月内有其他类型的帖子不应该显示。

    尽量包含

    AND post_type = 'post'
    

    进入用于选择年份和月份的查询中的 WHERE 子句。

    【讨论】:

      【解决方案2】:

      这就是我的做法:

       SELECT JAL.year, JAL.month, COUNT(JAL.ID) as `posts` FROM (" .
              "SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`,ID " .
              "FROM {$wpdb->posts} {$join} {$where}" .
       ") JAL GROUP BY JAL.year,JAL.month ORDER BY JAL.year,JAL.month DESC
      

      您选择所有帖子,然后每月提取其年份,然后按年份和月份对它们进行分组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-23
        • 2015-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-28
        相关资源
        最近更新 更多