jquery - Return an array from get_terms and store as JavaScript array for search autocomplete

admin2025-01-07  6

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.

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.

Share Improve this question asked Nov 26, 2016 at 7:23 NotoriousNotorious 1331 silver badge5 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

Solved it simply using:

$json = array();

    $terms = get_terms( 'state' );

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

    echo json_encode($json)

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);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736262408a816.html

最新回复(0)