要按类别显示自定义文章类型,可以使用WordPress的自定义文章类型(Custom Post Types)功能和分类法(Taxonomy)功能来实现。
首先,我们需要在主题的functions.php文件中添加以下代码来创建自定义文章类型:
function create_custom_post_type() {
register_post_type('custom_post_type',
array(
'labels' => array(
'name' => 'Custom Post Type',
'singular_name' => 'Custom Post Type'
),
'public' => true,
'has_archive' => true,
'supports' => array('title', 'editor', 'thumbnail'),
)
);
}
add_action('init', 'create_custom_post_type');
上述代码创建了一个名为"custom_post_type"的自定义文章类型。你可以根据自己的需求修改标签(labels)、支持的字段(supports)和其他选项。
接下来,我们需要创建一个新的分类法来对自定义文章类型进行分类。在functions.php文件中添加以下代码:
function create_custom_taxonomy() {
register_taxonomy(
'custom_taxonomy',
'custom_post_type',
array(
'label' => 'Custom Taxonomy',
'rewrite' => array('slug' => 'custom_taxonomy'),
'hierarchical' => true,
)
);
}
add_action('init', 'create_custom_taxonomy');
上述代码创建了一个名为"custom_taxonomy"的分类法,并将其与自定义文章类型"custom_post_type"关联起来。你可以根据自己的需求修改标签(label)、重写选项(rewrite)和其他选项。
现在,你可以在WordPress后台创建自定义文章类型的文章,并为其分配分类。在主题模板文件中,你可以使用以下代码来按类别显示自定义文章类型的文章:
$args = array(
'post_type' => 'custom_post_type',
'tax_query' => array(
array(
'taxonomy' => 'custom_taxonomy',
'field' => 'slug',
'terms' => 'category-slug' // 替换为你想要显示的分类别名
)
)
);
$custom_query = new WP_Query($args);
if ($custom_query->have_posts()) :
while ($custom_query->have_posts()) : $custom_query->the_post();
// 在这里显示自定义文章类型的文章
endwhile;
endif;
wp_reset_postdata();
上述代码中,我们使用WP_Query类来获取符合特定分类的自定义文章类型的文章。你需要将'terms'选项的值替换为你想要显示的分类别名。
将以上代码放置在你希望显示自定义文章类型的文章的地方,就可以按类别显示自定义文章类型的文章了。记得根据你的主题样式来自定义文章的显示方式。
上一篇:按类别显示成功百分比
下一篇:按类别显示供应商的产品