简体   繁体   中英

get posts using taxonomy in wordpress

I have a wordpress app locally setup in my computer. In the wordpress admin i have a Countries tab under the Posts. I'll attach an image for better understanding.

在此处输入图像描述

I want to write a function to get the country values for my front-end. For that i have written a function like this

    public function get_destinations()
    {

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

But for some reason this function returns all the posts in the database. I want to get only the country names.

i found the taxonomy from my local url which is

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

I'm very new to wordpress and dont have a clue on how to retrieve these data to my front end. What am i doing wrong here?

If you want to show the only category or taxonomy name instead of get_posts you have to use get_terms

check this code.

// 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
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM