如何使用自定义模板限制wordpress中显示的类别数量?

时间:2017-05-31 08:41:09

标签: php wordpress

自定义模板中的代码是   

$categories = get_categories( array(
'hide_empty'       => 0
) );

foreach ($categories as $cat) : ?>
<div class="fusion-one-third fusion-layout-column fusion-spacing-yes">

    <a href="<?php echo get_category_link($cat->term_id); ?>">
        <img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" />
        <h1 class="customp"><?php echo $cat->cat_name; ?></h1>
    </a>
</div>
<?php endforeach; ?>

它显示了所创建的每个类别,但我想只显示6个最新类别。无论这些类别是否有任何帖子。

3 个答案:

答案 0 :(得分:0)

我认为您可以使用该功能设置任何LIMIT选项。

作为替代方案,您可以使用PHP函数对其进行切片:

$categories = get_categories( array(
'hide_empty'       => 0
) );

$number_of_categories = 6 // Whatever you want to 
$categories = array_slice($categories, 0, $number_of_categories, true);

foreach ($categories as $cat) : ?>
<div class="fusion-one-third fusion-layout-column fusion-spacing-yes">

    <a href="<?php echo get_category_link($cat->term_id); ?>">
        <img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" />
        <h1 class="customp"><?php echo $cat->cat_name; ?></h1>
    </a>
</div>
<?php endforeach; ?>

试试!!

答案 1 :(得分:0)

谢谢大家,我使用了反击,它运作得很好。     

$categories = get_categories( array(
    'hide_empty'       => 0,
    'parent'  => 0
) );
$limit=6;
$counter=0;
foreach ($categories as $cat) : 
if($counter<$limit){

    ?>
<div class="fusion-one-third fusion-layout-column fusion-spacing-yes">

    <a href="<?php echo get_category_link($cat->term_id); ?>">
        <img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" />
        <h1 class="customp"><?php echo $cat->cat_name; ?></h1>
    </a>
</div>
<?php $counter++;
                }
 endforeach; ?>

答案 2 :(得分:-1)

我认为你可以使用get_terms render(){ return ( <div> {this.state.data.map((val, idx) => ( <div className="col-md-3"> ... rest of card ... </div> ))} </div> ) } 参数来限制类别数量,offsetorderby参数来获取最新的参数:

order