在 WordPress 里 http://localhost/wordpress3.6.1/wp-admin/edit-tags.php?taxonomy=category 这个链接可以显示 WP 里的无限栏目分类,我们来研究一下 WordPress 是如何实现的。
找到 wp-admin/edit-tags.php 这个文件,发现显示栏目的代码很少:
<?php $wp_list_table->display(); ?>
其实关键的是 $wp_list_table->display(); 这一行代码。
wordpress 的类库 wp_list_table 自始至终都是用来显示数据,例如用户,插件,评论或是文章,这个类库包含了几乎所有的用于显示、排序、分页和搜索的方法。
我们继续追踪下,打开 wp-admin/includes/class-wp-list-table.php 这个文件,找到 display(); 方法:
/**
* Display the table
*
* @since 3.1.0
* @access public
*/
function display() {
extract( $this->_args );
$this->display_tablenav( 'top' );
?>
<?php $this->print_column_headers(); ?>
<?php $this->print_column_headers( false ); ?>
><?php $this->display_rows_or_placeholder(); ?>
$this->display_tablenav( 'bottom' );
}
我们再着眼于生成栏目分类的下面这几行代码:
><?php $this->display_rows_or_placeholder(); ?>
display_rows_or_placeholder() 这个函数又是怎么回事呢?
/**
* Generate the
part of the table*
* @since 3.1.0
* @access protected
*/
function display_rows_or_placeholder() {
if ( $this->has_items() ) {
$this->display_rows();
} else {
list( $columns, $hidden ) = $this->get_column_info();
echo '
';$this->no_items();
echo '
';}
}
接下来是 has_items() 这个函数,这个函数判断有没有数据需要显示:
/**
* Whether the table has items to display or not
*
* @since 3.1.0
* @access public
*
* @return bool
*/
function has_items() {
return !empty( $this->items );
}
如果有,就 display_rows() :
/**
* Generate the table rows
*
* @since 3.1.0
* @access protected
*/
function display_rows() {
foreach ( $this->items as $item )
$this->single_row( $item );
}
/**
* Generates content for a single row of the table
*
* @since 3.1.0
* @access protected
*
* @param object $item The current item
*/
function single_row( $item ) {
static $row_class = '';
$row_class = ( $row_class == '' ? ' class="alternate"' : '' );
echo '
';$this->single_row_columns( $item );
echo '
';}
/**
* Generates the columns for a single row of the table
*
* @since 3.1.0
* @access protected
*
* @param object $item The current item
*/
function single_row_columns( $item ) {
list( $columns, $hidden ) = $this->get_column_info();
foreach ( $columns as $column_name => $column_display_name ) {
$class = "class='$column_name column-$column_name'";
$style = '';
if ( in_array( $column_name, $hidden ) )
$style = ' style="display:none;"';
$attributes = "$class$style";
if ( 'cb' == $column_name ) {
echo '
';echo $this->column_cb( $item );
echo '
';}
elseif ( method_exists( $this, 'column_' . $column_name ) ) {
echo "
";echo call_user_func( array( &$this, 'column_' . $column_name ), $item );
echo "
";}
else {
echo "
";echo $this->column_default( $item, $column_name );
echo "
";}
}
}
也就是说,根据是否有子栏目先拼凑好栏目分类的 html,再通过 $wp_list_table->display(); 显示到前台。