首页 文章

Wordpress分类术语模板循环

提问于
浏览
0

我在我的网站上设置了6个自定义分类法,按以下方式注册(示例中的分类法命名为“主题”):

/* Topic */
add_action( 'init', 'register_taxonomy_topic' );
function register_taxonomy_topic() {

$labels = array( 
    'name' => _x( 'Topics', 'topic' ),
    'singular_name' => _x( 'Topic', 'topic' ),
    'search_items' => _x( 'Search Topics', 'topic' ),
    'popular_items' => _x( 'Popular Topics', 'topic' ),
    'all_items' => _x( 'All Topics', 'topic' ),
    'parent_item' => _x( 'Parent Topic', 'topic' ),
    'parent_item_colon' => _x( 'Parent Topic:', 'topic' ),
    'edit_item' => _x( 'Edit Topic', 'topic' ),
    'update_item' => _x( 'Update Topic', 'topic' ),
    'add_new_item' => _x( 'Add New Topic', 'topic' ),
    'new_item_name' => _x( 'New Topic Name', 'topic' ),
    'separate_items_with_commas' => _x( 'Separate topics with commas', 'topic' ),
    'add_or_remove_items' => _x( 'Add or remove topics', 'topic' ),
    'choose_from_most_used' => _x( 'Choose from the most used topics', 'topic' ),
    'menu_name' => _x( 'Topics', 'topic' ),
);

$args = array( 
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_in_nav_menus' => true,
    'show_ui' => true,
    'show_tagcloud' => true,
    'hierarchical' => true,

    'rewrite' => true,
    'query_var' => true
);

register_taxonomy( 'topic', array('post'), $args );
}

在这6种分类法中,有2到25种不同的术语 .

我正在尝试创建一个动态存档页面,当用户点击该术语的存档页面时,该页面将列出与特定术语关联的正确帖子 . 页面需要是动态的,即根据所选术语列出相关帖子,使用一个模板,而不是为每个术语创建一个模板文件(这将导致超过100个模板!)

以下是我的分类法结构的示例:

帖子类型:帖子,分类:主题,术语:一,二,三

我目前正在使用的循环如下,它似乎输出了一个文章列表,但我无法从这些帖子的来源解读,其中许多都是重复的!我的循环还指定了'主题',我需要它来动态生成内容,而不管正在查看的6个分类法和X个术语中的哪个 .

<?php //start by fetching the terms for the animal_cat taxonomy
$terms = get_terms( 'topic', array(
    'orderby'    => 'count',
    'hide_empty' => 0
) );
?>

<?php
// now run a query for each animal family
foreach( $terms as $term ) {

    // Define the query
    $args = array(
        'post_type' => 'post',
        'topic' => $term->slug
    );
    $query = new WP_Query( $args );

    // output the post titles in a list
    echo '<ul>';

        // Start the Loop
        while ( $query->have_posts() ) : $query->the_post(); ?>

        <li id="post-<?php the_ID(); ?>">
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>

        <?php endwhile;

    echo '</ul>';

    // use reset postdata to restore orginal query
    wp_reset_postdata();

} ?>

任何帮助非常感谢!

1 回答

  • 0

    您可以使用 category.php 来显示您的术语 .

    if ( have_posts() )
    {
        while ( have_posts() )
        {
            the_post();
    
            the_title();
            the_content();
        }
    }
    

    你可以查看template hierarchy

相关问题