<?php
/**
* Template Name: Custom Post Types List
*/
get_header();
// Custom code will go here
get_footer();
?>
创建生成的自定义帖子类型(CPT)列表下一步是生成您的CPT列表。这有一个核心功能:
get_post_types()
:
<?php get_post_types( $args, $output, $operator ); ?>
因此,例如,要按名称返回公共、自定义帖子类型,请执行以下操作:
$custom_post_types = get_post_types(
array(
// Set to FALSE to return only custom post types
\'_builtin\' => false,
// Set to TRUE to return only public post types
\'public\' => true
),
// Set to "objects", so we have the full CPT object
\'objects\'
);
现在,您的CPT包含在一个具有CPT对象数组的变量中。
创建CPT存档索引永久链接列表,因此下一步是获取CPT对象,并使用它们创建每个CPT存档索引的永久链接列表。还有一个核心功能:get_post_type_archive_link()
:
<?php get_post_type_archive_link( $posttype ); ?>
因此,我们只需遍历post类型名称的数组,然后检索每个类型的permalink:
foreach ( $custom_post_types as $custom_post_type ) {
$custom_post_type->permalink = get_post_type_archive_link( $custom_post_type->name );
}
然后,可以使用永久链接数组(URL)创建列表标记:
<ul>
<?php
foreach ( $custom_post_types as $custom_post_type ) {
echo \'<li>\';
echo \'<a href="\' . $custom_post_type->permalink . \'">\' . $custom_post_type->name . \'</a>\';
echo \'</li>\';
}
?>
</ul>
把所有这些放在一起
template-cpt-list.php
现在应该是这样:
<?php
/**
* Template Name: Custom Post Types List
*/
get_header();
// Get list of CPTs
$custom_post_types = get_post_types(
array(
// Set to FALSE to return only custom post types
\'_builtin\' => false,
// Set to TRUE to return only public post types
\'public\' => true
),
// Set to "objects", so we have the full CPT object
\'objects\'
);
// Add CPT permalinks to CPT objects
foreach ( $custom_post_types as $custom_post_type ) {
$custom_post_type->permalink = get_post_type_archive_link( $custom_post_type->name );
}
// Output CPT archive index permalinks list
echo \'<ul>\';
foreach ( $custom_post_types as $custom_post_type ) {
echo \'<li>\';
echo \'<a href="\' . $custom_post_type->permalink . \'">\' . $custom_post_type->name . \'</a>\';
echo \'</li>\';
}
echo \'</ul>\';
get_footer();
?>