在wordpress中使用分类法获取文章

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

我的电脑里有一个本地设置的wordpress应用程序。在wordpress管理中,我在帖子下有一个国家标签。为了更好的理解,我会附上一张图片。

enter image description here

我想写一个函数来获取前端的国家值。为此,我写了这样一个函数

    public function get_destinations()
    {

            $bookings = get_posts(
                array(
                    'taxonomy'=> 'country',
                    'numberposts' => -1,
                )
            );
            return $bookings;
    }

但由于某些原因,这个函数返回数据库中的所有帖子。我只想得到国家名称。

我从我的本地网址中找到了分类法,它是

http://localhost/my_project/wp-admin/edit-tags.php?taxonomy=country

我对wordpress很陌生,不知道如何将这些数据检索到我的前端。我在这里做错了什么?

javascript php wordpress wordpress-rest-api
1个回答
2
投票

如果你想显示唯一的类别或分类名称,而非 get_posts 你必须使用 get_terms

检查这个代码。

// Get the taxonomy's terms
    $terms = get_terms(
        array(
            'taxonomy'   => 'country',
            'hide_empty' => false, // show category even if dont have any post.
        )
    );

    // Check if any term exists
    if ( ! empty( $terms ) && is_array( $terms ) ) {
        // Run a loop and print them all
        foreach ( $terms as $term ) { ?>
            <a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
                <?php echo $term->name; ?>
            </a><?php
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.