在wordpress中动态地在循环中插入div

时间:2015-06-12 12:45:37

标签: php html wordpress

我在wordpress中有自定义功能,下面的代码用于显示自定义分类的缩略图。我想要实现的是我想在每六个图像之后动态插入一个div class="row"。我该怎么做呢?

               $max = 10; //number of categories to display
                $taxonomy = 'cp_recipe_category';
                $terms = get_terms($taxonomy, 'hide_empty=1');

                // Random order
                shuffle($terms);

                // Get first $max items
                $terms = array_slice($terms, 0, $max);

                // Sort by name
                usort($terms, function($a, $b){
                    return strcasecmp($a->name, $b->name);
                });

                // Echo random terms sorted alphabetically
                if ($terms) {
                    foreach($terms as $term) {
                        echo'<div class="vc_col-sm-2 wpb_column vc_column_container ">';  
                        echo'<img src="'; echo z_taxonomy_image_url($term->term_id); echo'" />';  
                        echo '<p><a href="' .get_term_link( $term, $taxonomy ) . '" title="' .  sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a>
                        </p> ';
                        echo'</div>';


                    }
                }

3 个答案:

答案 0 :(得分:1)

喜欢什么?

            $max = 10; //number of categories to display
            $taxonomy = 'cp_recipe_category';
            $terms = get_terms($taxonomy, 'hide_empty=1');

            // Random order
            shuffle($terms);

            // Get first $max items
            $terms = array_slice($terms, 0, $max);

            // Sort by name
            usort($terms, function($a, $b){
                return strcasecmp($a->name, $b->name);
            });

            // Echo random terms sorted alphabetically
            if ($terms) {
                $i = 0;
                foreach($terms as $term) {
                    $i++;
                    echo'<div class="vc_col-sm-2 wpb_column vc_column_container ">';  
                    echo'<img src="'; echo z_taxonomy_image_url($term->term_id); echo'" />';  
                    echo '<p><a href="' .get_term_link( $term, $taxonomy ) . '" title="' .  sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a>
                    </p> ';
                    echo'</div>';
                    if($i%6 == 0) { echo '<div class="row"></div>'; }


                }
            }

答案 1 :(得分:0)

以下是如何实现这一目标:

$r = 0;
foreach($terms as $term) {

    if($r ==5)
       {
         //add your div
         $r = 0;
       }
   else
        $r++;
  }

答案 2 :(得分:0)

试试这个:

$i = 1;
//added before to ensure it gets opened
echo '<div>';
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
     // post stuff...

     // if multiple of 3 close div and open a new div
     if($i % 3 == 0) {echo '</div><div>';}

$i++; endwhile; endif;
//make sure open div is closed
echo '</div>';