Functions的妙用:将文章自动显示为两列
很多博客都有一行显示多个post文章的样式,他的原理其实非常简单,今天找到一段php代码,只需在functions.php文件中添加上,那么你的文章也会多列显示,非常实用!
1.PHP代码:
打开functions.php文件,添加如下的php代码,通过判断是否是第二次输出来给出左右浮动的div标签。
- <?php
- function my_multi_col($content){
- $columns = explode("<h2>", $content);
- $i = 0;
- foreach ($columns as $column) {
- if (($i % 2) == 0){
- $return .= '<div class="content_left">';
- if ($i > 1){
- $return .= "<h2>";
- } else{
- $return .= '<div class="content_right"><h2>';
- }
- $return .= $column;
- $return .= "</h2></div>";
- $i++;
- }
- if(isset($columns[1])){
- $content = wpautop($return);
- }else{
- $content = wpautop($content);
- }
- echo $content;
- }
- }
- add_filter('the_content', 'my_multi_col');
- ?>
- </h2></div>
代码中的h2是你的每个文章标题所包含的标签。
2.CSS代码:
完成在functions.php文件中添加好上面的代码后,记得打开style.css文件,添加上样式代码。
- .content_right, .content_left {
- width:45%;
- }
- .content_left {
- float:left;
- }
- .content_right {
- float:right;
- }
那么同理,我们可以根据判断$i变量来输出3列、4列等。
本文转载自:http://www.ihiro.org/wordpress-the-article-automatically-appear-as-two


不错。php这个有点深奥。