【问题标题】:Can't get only 5 terms to display in Wordpress?无法在 Wordpress 中仅显示 5 个术语?
【发布时间】:2014-12-29 03:07:44
【问题描述】:

所以我试图在链接到术语链接的列表项中仅显示 5 个随机子术语。我很接近,但我似乎不能只显示 5。

这是我的代码:

<?php 
    $terms = get_terms( 'types' );

    echo '<ul>';

    // shuffle!
    shuffle( $terms );

    // slice the array
    array_slice($terms, 0, 4);

    foreach ( $terms as $term ) {

        // The $term is an object, so we don't need to specify the $taxonomy.
        $term_link = get_term_link( $term );

        // If there was an error, continue to the next term.
        if ( 0 == $term->parent ) {
            continue;
        }

        // We successfully got a link. Print it out.
        echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a></li>';
    }

    echo '</ul>'; 
?>

我尝试在随机播放后使用array_slice,但它似乎不起作用。

有什么建议吗?

【问题讨论】:

    标签: php html css wordpress slice


    【解决方案1】:

    只需将 array_slice 结果返回到变量中,例如 $terms 就像这样

       $terms = array_slice($terms, 0, 4);
    
       var_dump($terms); //see you have 5 elements
    

    【讨论】:

    • 愿意给我一个使用我上面代码的例子吗?因为我已经在顶部有$terms = get_terms( 'types' );
    • 在我的示例中,array_slice 会覆盖您之前来自 get_terms()$terms 变量。如果您不想覆盖 $terms-variable,请使用新变量,例如$sliced = array_slice($terms, 0, 4);,然后在 foreach 中使用 foreach( $sliced as $term) {...}。希望这会有所帮助!
    • @LucasSantos 你明白我想说什么了吗?
    • 这是正确答案。 @pbaldauf 建议您将当前的 array_slice() 函数分配给一个变量。
    • @LucasSantos。只需将 $array_slice() 函数分配给您选择的变量即可。你的代码很好。我想这个问题现在可以结束了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 2020-09-13
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多