【问题标题】:get posts using taxonomy in wordpress在 wordpress 中使用分类法获取帖子
【发布时间】:2020-08-06 15:26:32
【问题描述】:

我在我的计算机上本地设置了一个 wordpress 应用程序。在 wordpress 管理员中,我在帖子下有一个国家选项卡。我会附上一张图片以便更好地理解。

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

    public function get_destinations()
    {

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

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

我从我的本地 url 中找到了分类法

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

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

【问题讨论】:

    标签: javascript php wordpress wordpress-rest-api


    【解决方案1】:

    如果您想显示唯一的类别或分类名称而不是 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
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多