【发布时间】:2020-10-20 22:20:43
【问题描述】:
我正在尝试弄清楚如何将我的自定义分类类别添加到模板页面,并让它们链接到该类别的所有自定义帖子类型。
这是我目前所拥有的。我创建了一个插件来保存创建自定义帖子类型 (contractor) 和自定义帖子分类类别 (contractor_category) 的函数。就我有一个列出所有承包商的模板页面(page-contractors-full-width.php)而言,这是有效的。在页面顶部,我有一个列出所有自定义类别(contractor_category)的循环。问题是链接将转到 404 页面。我无法弄清楚每个自定义类别的 slug 应该是什么。我试过 /contractor/contractor_category 和 /contractor_category
我尝试创建archive-contractor.php 和archive-contractor_category.php 和taxonomy-contractor_category.php 只是为了看看它们中的任何一个是否可以工作,但它们没有工作。我已经阅读了有关此的 wordpress 文档,但这有点超出我的想象。我最好看例子哈哈..
这是我的插件代码,用于创建自定义帖子类型和自定义分类
add_action( 'init', 'create_contractor_category_tax' );
function create_contractor_category_tax() {
register_taxonomy(
'contractor_category',
'contractor',
array(
'label' => __( 'Contractor Category' ),
'rewrite' => array( 'slug' => 'contractor_category' ),
'hierarchical' => true,
)
);
}
function nari_post_type_contractor() {
$supports = array(
'title', // post title
'editor', // post content
'author', // post author
'thumbnail', // featured images
'excerpt', // post excerpt
'custom-fields', // custom fields
'comments', // post comments
'revisions', // post revisions
'post-formats', // post formats
);
$labels = array(
'name' => _x('Contractors', 'plural'),
'singular_name' => _x('Contractor', 'singular'),
'menu_name' => _x('Contractors', 'admin menu'),
'name_admin_bar' => _x('Contractors', 'admin bar'),
'add_new' => _x('Add New', 'add new'),
'add_new_item' => __('Add New Contractor'),
'new_item' => __('New Contractor'),
'edit_item' => __('Edit Contractor'),
'view_item' => __('View Contractor'),
'all_items' => __('All Contractors'),
'search_items' => __('Search Contractors'),
'not_found' => __('No Contractors found.'),
);
$args = array(
'supports' => $supports,
'labels' => $labels,
'public' => true,
'query_var' => true,
'rewrite' => array('slug' => 'contractor'),
'has_archive' => true,
'hierarchical' => false,
);
register_post_type('contractor', $args);
}
add_action('init', 'nari_post_type_contractor');
这是我循环并获取自定义分类链接的代码
// Get the taxonomy's terms
$terms = get_terms(
array(
'taxonomy' => 'contractor_category',
'hide_empty' => true,
)
);
// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
// add links for each category
foreach ( $terms as $term ) { ?>
<a class="btn btn-default" href="<?php echo esc_url( get_term_link( $term ) ) ?>">
<?php echo $term->name; ?>
</a><?php
}
}
任何帮助将不胜感激:)
【问题讨论】:
标签: php wordpress custom-taxonomy