在 WordPress 里 http://localhost/wordpress3.6.1/wp-admin/edit-tags.php?taxonomy=category 这个链接可以显示 WP 里的无限栏目分类,我们来研究一下 WordPress 是如何实现的。
找到 wp-admin/edit-tags.php 这个文件,发现显示栏目的代码很少:
1 |
<form id="posts-filter" action="" method="post"> |
2 |
<input type="hidden" name="taxonomy" value="<?php echo esc_attr($taxonomy); ?>" /> |
3 |
<input type="hidden" name="post_type" value="<?php echo esc_attr($post_type); ?>" /> |
5 |
<?php $wp_list_table->display(); ?> |
其实关键的是 $wp_list_table->display(); 这一行代码。
wordpress 的类库 wp_list_table 自始至终都是用来显示数据,例如用户,插件,评论或是文章,这个类库包含了几乎所有的用于显示、排序、分页和搜索的方法。
我们继续追踪下,打开 wp-admin/includes/class-wp-list-table.php 这个文件,找到 display(); 方法:
08 |
extract( $this->_args ); |
10 |
$this->display_tablenav( 'top' ); |
13 |
<table class="wp-list-table <?php echo implode( ' ', $this->get_table_classes() ); ?>" cellspacing="0"> |
16 |
<?php $this->print_column_headers(); ?> |
22 |
<?php $this->print_column_headers( false ); ?> |
26 |
<tbody id="the-list"<?php if ( $singular ) echo " data-wp-lists='list:$singular'"; ?>> |
27 |
<?php $this->display_rows_or_placeholder(); ?> |
31 |
$this->display_tablenav( 'bottom' ); |
我们再着眼于生成栏目分类的下面这几行代码:
1 |
<tbody id="the-list"<?php if ( $singular ) echo " data-wp-lists='list:$singular'"; ?>> |
2 |
<?php $this->display_rows_or_placeholder(); ?> |
display_rows_or_placeholder() 这个函数又是怎么回事呢?
07 |
function display_rows_or_placeholder() { |
08 |
if ( $this->has_items() ) { |
09 |
$this->display_rows(); |
11 |
list( $columns, $hidden ) = $this->get_column_info(); |
12 |
echo '<tr class="no-items"><td class="colspanchange" colspan="' . $this->get_column_count() . '">'; |
接下来是 has_items() 这个函数,这个函数判断有没有数据需要显示:
09 |
function has_items() { |
10 |
return !empty( $this->items ); |
如果有,就 display_rows() :
07 |
function display_rows() { |
08 |
foreach ( $this->items as $item ) |
09 |
$this->single_row( $item ); |
20 |
function single_row( $item ) { |
21 |
static $row_class = ''; |
22 |
$row_class = ( $row_class == '' ? ' class="alternate"' : '' ); |
24 |
echo '<tr' . $row_class . '>'; |
25 |
$this->single_row_columns( $item ); |
37 |
function single_row_columns( $item ) { |
38 |
list( $columns, $hidden ) = $this->get_column_info(); |
40 |
foreach ( $columns as $column_name => $column_display_name ) { |
41 |
$class = "class='$column_name column-$column_name'"; |
44 |
if ( in_array( $column_name, $hidden ) ) |
45 |
$style = ' style="display:none;"'; |
47 |
$attributes = "$class$style"; |
49 |
if ( 'cb' == $column_name ) { |
50 |
echo '<th scope="row" class="check-column">'; |
51 |
echo $this->column_cb( $item ); |
54 |
elseif ( method_exists( $this, 'column_' . $column_name ) ) { |
55 |
echo "<td $attributes>"; |
56 |
echo call_user_func( array( &$this, 'column_' . $column_name ), $item ); |
60 |
echo "<td $attributes>"; |
61 |
echo $this->column_default( $item, $column_name ); |
也就是说,根据是否有子栏目先拼凑好栏目分类的 html,再通过 $wp_list_table->display(); 显示到前台。