以前介绍了短代码的使用方法和如何集成到wordpress后台html编辑器中,今天就介绍一个具体的应用,利用短代码插入表格到文章中。
在这之前有必要说一下,先要禁用wpautop函数,否则页面中的html标签将会干扰一下短代码的使用。具体可以参考我这篇文章:
wordrpess中wpautop函数的使用及禁用
表格插入php代码
老规矩,还是要在functions.php里写好短代码,下面给出表格插入的短代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
//表格短代码 add_shortcode( 'table', 'table_shortcode_handler' ); function table_shortcode_handler( $atts, $content='' ) { extract( shortcode_atts( array( 'border' => '0.5', 'cellpading' => '0', 'cellspacing' => '0', 'class' => 'shorttable', 'width' => '' ), $atts ) ); $output = ''; $trs = explode("\r\n\r\n", $content); $i=1; foreach($trs as $tr){ $tr = trim($tr); if($tr){ $tds = explode("\r\n", $tr); if($i!=1) $output .= '<tr>'; else $output .= '<tr class="head">'; foreach($tds as $td){ $td = trim($td); if($td){ $output .= '<td>'.$td.'</td>'; } } $output .= '</tr>'; } $i=$i+1; } if($class){ $class = ' class="'.$class.'"'; } if($width){ $width = ' width="'.$width.'"'; } $output = '<table border="'.$border.'" cellpading="'.$cellpading.'" cellspacing="'.$cellspacing.'" '.$width.' '.$class.' >'.$output.'</table>'; return $output; } |
大概的介绍下这段代码的意思:连续两个回车为一行(tr),一个回车为一个单元格(td),其中第一行为表头,单独定义了一个样式。
css样式化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
.shorttable { margin-bottom: 20px; border: 1px solid #CCCCCC; margin-bottom: 15px; } .shorttable tr { clear: both; list-style: none outside none; margin: 0; padding: 0; } .shorttable tr.head td { background: none repeat scroll 0 0 #F5F5F5; border-bottom: 1px solid #CCCCCC; color: #222222; } .shorttable tr td { border-bottom: 1px dotted #CCCCCC; border-right: 1px dotted #CCCCCC; font-size: 12px; line-height: 28px; text-align: center; } |
使用方法
在html编辑模式下插入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
[table width="95%"] 姓名 学号 年龄 性别 李明 1 20 男 李芳 2 21 女 [/table] |
效果如下:
姓名 | 学号 | 年龄 | 性别 |
李明 | 1 | 20 | 男 |
李芳 | 2 | 21 | 女 |
小结
php代码那部分参考了我爱水煮鱼的文章:http://blog.wpjam.com/m/wordpress-shortcode-for-table/,它的样式没有进行过优化,太难看了些。我针对表头单独定义了样式,美观些。