1

I am trying to use wp_list_pluck to return an array of taxonomy names from get_terms. I'm not sure what I'm doing wrong, but this only echo's out "Array":

$terms = get_terms(array(
        'taxonomy' => 'state',
        'hide_empty' => false,
    ));

    $term_ids = wp_list_pluck( $terms, 'name' );

    echo $term_ids;

Do you know how I can echo out an array of taxonomy names?

The reason I am doing this is because I am wanting to get an array to convert it to a Javascript array of names using json_encode.

Basically I'm using jQuery Autocomplete and would like to get my taxonomy names listed as suggestions to search for:

var availableTags = <?php echo json_encode( $term_ids ) ?>

Perhaps there is possibly a better way to achieve what I am trying to do? Thank-you.

2 Answers 2

0

Solved it simply using:

$json = array();

    $terms = get_terms( 'state' );

    foreach ( $terms as $term ) {
        $json[]=array( 'value'=> $term->name );
    }

    echo json_encode($json)
1
  • For an autocomplete script it's better to have label and value . Commented Nov 26, 2016 at 8:21
0

Simple mistake in your code wp_list_pluck() returns an array, not a single value. So when you echo $term_ids, you are trying to output an array directly, which PHP will only display as Array. Instead, you should use json_encode() to convert the array into a JSON string.

replace this line

echo $term_ids;

to

echo json_encode($term_ids);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.