如何在多个输出模板中将三个查询减少为一个?

时间:2012-10-27 作者:Francesco

我想发表7篇来自同一类别但嵌入不同DIV或UL的帖子。

如何简化此代码?

<?php
$query01 = array( \'numberposts\' => 1, \'offset\'=> 0, \'post_type\' => array(\'product\') );
$query02 = array( \'numberposts\' => 3, \'offset\'=> 1, \'post_type\' => array(\'product\') );
$query03 = array( \'numberposts\' => 3, \'offset\'=> 4, \'post_type\' => array(\'product\') );
?>

<div class="class news">
<ul class="280">
get_posts( $query01 ) -> FOREACH WITH ONE POST
</ul>
</div>

<div class="class editorial">
<ul class="650">
get_posts( $query02 ) -> FOREACH WITH THREE POST
</ul>
</div>

<div class="class images">
<ul class="980">
get_posts( $query03 ) -> FOREACH WITH THREE POST
</ul>
</div>

1 个回复
SO网友:Milo

一次查询所有帖子,并设置一个计数器变量来检查您在循环中的位置。

$products = get_posts(
    array( 
        \'numberposts\' => 7,
        \'post_type\' => array(\'product\')
    )
);
$count = 1;
foreach( $products as $product ):
    if( $count == 1 ):
        // first post
    elseif( $count > 1 && $count < 5 ):
        // two - four
    else:
        // four +
    endif;
    $count++;
endforeach;
编辑-使用标记:

$products = get_posts(
    array( 
        \'numberposts\' => 7,
        \'post_type\' => array(\'product\')
    )
);

?>
<div class="class news">
<ul class="280">
<?php
$count = 1;
foreach( $products as $product ):
    if( $count == 2 ):
        ?>
        </ul>
        </div>

        <div class="class editorial">
        <ul class="650">
        <?php
    elseif( $count == 5 ):
        ?>
        </ul>
        </div>

        <div class="class images">
        <ul class="980">
        <?php
    endif;

    echo \'<li>post</li>\';
    $count++;
endforeach;
?>
</ul>
</div>

结束

相关推荐

在函数.php中使用wp_mail

在整理完整的实现之前,我已经设置了一个简单的邮件程序。我尝试了一些电子邮件地址,但没有收到它们,即使它返回“true”。如果这有什么不同的话,我也在使用wp\\uajax。功能。php // Check for email return in share folders add_action( \'wp_ajax_share_email\', \'share_email\' ); add_action( \'wp_ajax_nopriv_shar