Wordpress get_the_terms用于自定义分类

问题描述 投票:1回答:1

在存档页面中,我试图显示自定义分类(称为位置)以及每个帖子标题,类别和标记。我不能让'get_the_terms'工作。

帖子标题,类别和标签运作完美。分类法不起作用。

<div class="post-listing">
        <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
        <p><?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?></p>
        <p><?php $tags = get_the_tags(); foreach($tags as $tag) { echo "$tag->name"; } ?></p>
        <p><?php $terms = get_the_terms( 'locations' ); foreach($terms as $term) { echo "$term->name"; } ?></p>
</div>

这是我的functions.php代码。

//hook into the init action and call create_locations_nonhierarchical_taxonomy when it fires
    add_action( 'init', 'create_locations_nonhierarchical_taxonomy', 0 );
    function create_locations_nonhierarchical_taxonomy() {
    // Labels part for the GUI
      $labels = array(
        'name' => _x( 'Locations', 'taxonomy general name' ),
        'singular_name' => _x( 'Location', 'taxonomy singular name' ),
        'search_items' =>  __( 'Search Locations' ),
        'popular_items' => __( 'Popular Locations' ),
        'all_items' => __( 'All Locations' ),
        'parent_item' => null,
        'parent_item_colon' => null,
        'edit_item' => __( 'Edit Location' ), 
        'update_item' => __( 'Update Location' ),
        'add_new_item' => __( 'Add New Location' ),
        'new_item_name' => __( 'New Location Name' ),
        'separate_items_with_commas' => __( 'Separate locations with commas' ),
        'add_or_remove_items' => __( 'Add or remove locations' ),
        'choose_from_most_used' => __( 'Choose from the most used locations' ),
        'menu_name' => __( 'Locations' ),
      ); 
    // Now register the non-hierarchical taxonomy like tag
      register_taxonomy('locations','post',array(
        'hierarchical' => false,
        'labels' => $labels,
        'show_ui' => true,
        'show_admin_column' => true,
        'update_count_callback' => '_update_post_term_count',
        'query_var' => true,
        'rewrite' => array( 'slug' => 'location' ),
      ));
    }

有任何想法吗?这让我很生气!

wordpress taxonomy
1个回答
2
投票

get_the_terms函数有两个参数。它们是$ post和$ taxonomy。与其他“get_the_xxxx”函数不同,您可以跳过循环内的$ post(post对象或post ID)参数,您必须将post对象或post ID添加到第一个参数。

我想你应该写

$terms = get_the_terms( $post, 'locations' );

代替

$terms = get_the_terms( 'locations' );

文档:https://developer.wordpress.org/reference/functions/get_the_terms/

© www.soinside.com 2019 - 2024. All rights reserved.