问题描述

我一直在搜索 Google,这是无济于事。

我正在一个餐馆的网站上工作,我有一个定制的帖子类型的菜肴,如:

$args = array(
    'labels'=> $labels,
    'public'=> true,
    'publicly_queryable'=>true,
    'show_ui'=>true,
    'show_in_nav_menus'=>true,
    'query_var'=>'dish',
    'rewrite'=>true,
    'capability_type'=>'post',
    'hierarchicial'=>false,
    'menu_position'=>5,
    'supports'=>array(
        'title',
        'editor',
        'thumbnail',
        'excerpt',
        'custom-fields',
        'revisions'
    )
);

register_post_type('dish', $args);

我想使用的一个自定义分类法的一个例子是:

register_taxonomy('Main Ingredient', array('dish'), array(
    'hierarchical' => true,
    'label' => 'Main Ingredient',
    'singular_label' => 'Main Ingredient',
    'query_var'=>true,
    'rewrite' => true)
);

自定义分类法在管理员中可以正常工作,我可以去 myurl.com/main-ingredient/pork 看看所有的猪肉菜肴列表。

我想要做的是能够打到 myurl.com/main-ingredient 并获得所有各种 main-ingredient 值的列表。

我发现这个参考,这正是我正在做的:Custom taxonomy listing page when no term set (all terms)

但解决方案对我来说并不奏效 – 当我去 myurl.com/main-ingredient 时,我仍然会收到 404

关于如何最好地做到这一点的任何建议?

最佳解决方案

没有任何内置到 WordPress 为您的分类提供一个”index” 页面,因为您的问题意味着应该有 (我同意,应该是!但没有。)

相反,你必须破解它,一种方法是创建一个名为”Main Ingredient” 的页面,其中包含一个 main-ingredient URL 段,并为您创建的主题 (可能称为 “主要成分列表”) 分配一个页面模板

这是一个起点; 也可以使用文件名 page-main-ingredient-list.php 作为您的页面模板:

<?php
/*
Template Name: Main Ingredient List
*/
get_header();
$main_ingredients = get_terms('main-ingredient');
foreach($main_ingredients as $main_ingredient) {
  $dishes = new WP_Query(array(
    'post_type' => 'dish',
    'post_per_page'=>-1,
    'taxonomy'=>'main-ingredient',
    'term' => $main_ingredient->slug,
  ));
  $link = get_term_link(intval($main_ingredient->term_id),'main-ingredient');
  echo "<h2><a href="{$link}">{$main_ingredient->name}</a></h2>";
  echo '<ul>';
  while ( $dishes->have_posts() ) {
    $dishes->the_post();
    $link = get_permalink($post->ID);
    $title = get_the_title();
    echo "<li><a href="{$link}">{$title}</a></li>";
  }
  echo '</ul>';
}
get_footer();

那么这个页面看起来像我的测试网站上的一些虚拟数据:

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。