Wrap every month posts in div

时间:2016-11-28 作者:th3rion

我有一个代码,在div中每4篇文章就包装一次。我如何调整它以在div中每月包装一篇文章。

<?php
$args = array(
    \'post_type\' => \'posts\',
    \'posts_per_page\' => -1,
    \'order\' => \'DESC\'
);

$the_query = new WP_Query($args);
if ($the_query->have_posts()) :
    $counter = 0;
    while ($the_query->have_posts()) : $the_query->the_post();
        if ($counter % 4 == 0) :
            echo $counter > 0 ? "</div>" : ""; 
            echo "<div class=\'row\'>";
        endif;
        ?>
        <div class="col-3">
            <?php the_title(); ?>
        </div>
        <?php
        $counter++;

    endwhile;
endif;
wp_reset_postdata();
?>

2 个回复
最合适的回答,由SO网友:TheDeadMedic 整理而成
$last_month = null;

while ( $the_query->have_posts() ) :
    $the_query->the_post();
    $the_month = get_the_time( \'Ym\' ); // e.g. 201611

    if ( $last_month !== $the_month ) {
        if ( $last_month !== null ) {
            // Close previously opened <div class="row" />
            echo \'</div>\';
        }

        echo \'<div class="row">\';
    }

    $last_month = $the_month;

    ?>

    <div class="col-3">
        <?php the_title(); ?>
    </div>

    <?php

    if ( $the_query->current_post + 1 === $the_query->post_count ) {
        // Last item, always close the div
        echo \'</div>\';
    }

endwhile;
SO网友:th3rion

@死亡医生感谢你的帮助。代码当然有效。我还想改变第一组的风格,所以我增加了帖子数量。以下是完整代码:

<?php

    $args = array(
        \'post_type\' => \'post\',
        \'posts_per_page\' => -1,
        \'order\' => \'DESC\'
    );

    $the_query = new WP_Query($args);
    if ($the_query->have_posts()) :     

        $last_month = null;
        $postCount = 1;

        while ( $the_query->have_posts() ) : $postCount++;
            $the_query->the_post();
            $the_month = get_the_time( \'Ym\' ); 

            if ( $last_month !== $the_month ) {
                if ( $last_month !== null ) {

                    echo \'</div>\';
                }

?>      

<?php if($postCount == 2) { ?>

        <div class="firstgroup"> // style first group of posts

<?php } else { ?>

        <div class="othergroups"> // style other groups of posts

<?php } ?>

<?php               

            }

            $last_month = $the_month;

            ?>

            <div>

                <?php the_title(); ?>

            </div>

            <?php

            if ( $the_query->current_post + 1 === $the_query->post_count ) {
                // Last item, always close the div
                echo \'</div>\';
            }

        endwhile;

    endif;

    wp_reset_postdata();

?>

相关推荐

浏览器刷新时删除数据库条目,AJAX PHP jQuery

我有一个表单,在通过ajax提交表单时更新数据库表中的列。一切都很好,数据库表列可以获取信息,但一旦刷新浏览器,信息就会从数据库中删除。如果meta\\u值不存在,但meta\\u值也在提交表单时创建的数据库中,则PHP将执行数据库更新。我希望信息保留在数据库中,直到或除非meta\\u值被删除或不存在。任何见解都将不胜感激。PHPadd_action(\'wp_ajax_hide_this\', \'hide_this_by_id\'); add_action(\'wp_ajax_nopriv_