首先,您需要获取所有没有父级的类别(顶级类别)。我们将使用get_terms
为了这个。Get terms将返回一个空数组WP_Error
对象,或表示术语的对象数组。因此,在继续之前,我们需要确保我们的通话正常。
<?php
// very hackish get_terms call with the 0 as a string to return top level terms
$cats = get_terms( \'category\', array( \'parent\' => \'0\' ) );
if( ! $cats || is_wp_error( $cats ) ) return;
有了它,我们可以首先输出一个容器div,然后启动
foreach
循环遍历所有类别。我们将根据您的要求在段落内输出术语和链接。
<?php
$out = \'<div id="ref-list">\' . "\\n";
foreach( $cats as $cat )
{
$out .= sprintf(
\'<p class="lit-author"><a href="%s">%s</a></p>\',
esc_url( get_term_link( $cat ) ),
sanitize_term_field( \'name\', $cat->name, $cat->term_id, \'category\', \'display\' )
);
$out .= "\\n"; // add some newlines to prettify our source
仍然在我们的
foreach( $cats as $cat )
循环,我们可以为足月儿童循环。如果我们找到它们,我们将遍历每个子级,获取其链接、名称和描述。
<?php
$children = get_term_children( $cat->term_id, \'category\' );
if( $children && ! is_wp_error( $children ) )
{
foreach( $children as $child )
{
$child = get_term( $child, \'category\' );
if( is_wp_error( $child ) ) continue;
$out .= sprintf(
\'<p class="lit-work"><a href="%s"><em>%s</em></a>. %s</p>\',
esc_url( get_term_link( $child ) ),
sanitize_term_field( \'name\', $child->name, $child->term_id, \'category\', \'display\' ),
esc_attr( $child->description ) // sanitize_term_field adds autop, no good for this situation
);
$out .= "\\n"; // prettifying newline
}
}
} // end of the foreach( $cats as $cat ) loop
$out .= "</div>\\n";
return $out;
您可以将整个混乱封装在一个函数中(注意:这里添加了计数,上面忘记了计数)。
<?php
function wpse25157_ref_list()
{
// very hackish get_terms call with the 0 as a string to return top level terms
$cats = get_terms( \'category\', array( \'parent\' => \'0\' ) );
if( ! $cats || is_wp_error( $cats ) ) return;
$out = \'<div id="ref-list">\' . "\\n";
foreach( $cats as $cat )
{
$out .= sprintf(
\'<p class="lit-author"><a href="%s">%s</a> (%s)</p>\',
esc_url( get_term_link( $cat ) ),
sanitize_term_field( \'name\', $cat->name, $cat->term_id, \'category\', \'display\' ),
sanitize_term_field( \'count\', $cat->count, $cat->term_id, \'category\', \'display\' )
);
$out .= "\\n"; // add some newlines to prettify our source
$children = get_term_children( $cat->term_id, \'category\' );
if( $children && ! is_wp_error( $children ) )
{
foreach( $children as $child )
{
$child = get_term( $child, \'category\' );
if( is_wp_error( $child ) ) continue;
$out .= sprintf(
\'<p class="lit-work"><a href="%s"><em>%s</em></a>. %s (%s)</p>\',
esc_url( get_term_link( $child ) ),
sanitize_term_field( \'name\', $child->name, $child->term_id, \'category\', \'display\' ),
esc_attr( $child->description ),
sanitize_term_field( \'count\', $child->count, $child->term_id, \'category\', \'display\' )
);
$out .= "\\n"; // prettifying newline
}
}
} // end of the foreach( $cats as $cat ) loop
$out .= "</div>\\n";
return $out;
}
并添加一个短代码,以便在您喜欢的任何页面/帖子上显示所有内容。
<?php
add_action( \'init\', \'wpse25157_init\' );
function wpse25157_init()
{
add_shortcode( \'ref-list\', \'wpse25157_ref_list\' );
}
作为插件:
https://gist.github.com/1196457