将自定义帖子列表拆分为两列

时间:2013-01-29 作者:user26724

有人能帮我把这个自定义帖子类型分成两个列表吗?我是一个PHPr新手,但有人告诉我这段代码太复杂了。。。

function listforcontinent($name, $top = false){
    // top=true - show name, no columns
    // top=false - dont show name, columns

    $slugname = sanitize_title($name);
    $args = array(\'tax_query\' => array(array(

                                             \'taxonomy\' => \'jurisdiction_continents\',
                                             \'field\' => \'slug\',
                                             \'terms\' => $slugname)), 
                                             \'post_type\' => \'jurisdiction\',
                                             \'orderby\' => \'title\', 
                                             \'posts_per_page\' => 35,
                                             \'order\' => \'ASC\');

    $postslist = get_posts( $args );
    if ($postslist) {
        if($top) echo \'<h4>\'.$name.\'</h4>\';
        echo \'<ul>\';
        foreach ( $postslist as $post ) {
            setup_postdata($post);
            echo \'<li><a href="\'.get_permalink($post->ID).\'">\'.get_the_title($post->ID)."</a></li>";
        }
        echo \'</ul>\';
    }else{
        if($top) echo \'<h4>\'.$name.\'</h4>\';
    }                               
}
非常感谢您的帮助,谢谢:)

2 个回复
最合适的回答,由SO网友:fuxia 整理而成

您可以计算项目数并插入</ul><ul> 50%之后。

未测试的示例代码:

if ($postslist) {

    $count = 1;

    if($top) echo \'<h4>\'.$name.\'</h4>\';
    echo \'<ul>\';
    foreach ( $postslist as $post ) {
        echo \'<li><a href="\'.get_permalink($post->ID).\'">\'.get_the_title($post->ID)."</a></li>";
        if ( 0 === $count % 10 )
            echo \'</ul><ul>\';

        $count += 1;
    }
    echo \'</ul>\';
}
你不需要setup_postdata($post); 在这里

SO网友:Michael

要避免在有10个列表项的精确倍数的情况下获得空的无序列表,并在不考虑其长度的情况下将帖子列表一分为二,但在第一个无序列表中至少有10个项目,请尝试以下代码:

if ($postslist) {

    $count = 0; 
    $half = max( 10, ceil( count( $postslist )/2 ) );

    if($top) echo \'<h4>\'.$name.\'</h4>\';
    echo \'<ul>\';
    foreach ( $postslist as $post ) {

        if ( $count != 0 && 0 === $count % $half )
            echo \'</ul><ul>\';

            echo \'<li><a href="\'.get_permalink($post->ID).\'">\'.$post.get_the_title($post->ID)."</a></li>";
        $count += 1;

         }
    echo \'</ul>\';
}

结束