Question

I need array terms of taxonomy in my post (single.php). I'm trying with

<?php $term_list = wp_get_post_terms($post->ID, 'agencia', array("fields" => "names")); print_r($term_list); ?>

But html out is:

Array ( [0] => Agencia 1 )

I want show only "Agencia 1", and if have 2 terms, must show "Agencia 1, Agencia 2"

What are i doing wrong?

creating taxonomy:

// Register Custom Taxonomy function custom_taxonomy() {

$labels = array(
    'name'                       => _x( 'Agencias', 'Taxonomy General Name', 'text_domain' ),
    'singular_name'              => _x( 'Agencia', 'Taxonomy Singular Name', 'text_domain' ),
    'menu_name'                  => __( 'Genre', 'text_domain' ),
    'all_items'                  => __( 'All Genres', 'text_domain' ),
    'parent_item'                => __( 'Parent Genre', 'text_domain' ),
    'parent_item_colon'          => __( 'Parent Genre:', 'text_domain' ),
    'new_item_name'              => __( 'New Genre Name', 'text_domain' ),
    'add_new_item'               => __( 'Add New Genre', 'text_domain' ),
    'edit_item'                  => __( 'Edit Genre', 'text_domain' ),
    'update_item'                => __( 'Update Genre', 'text_domain' ),
    'separate_items_with_commas' => __( 'Separate genres with commas', 'text_domain' ),
    'search_items'               => __( 'Search genres', 'text_domain' ),
    'add_or_remove_items'        => __( 'Add or remove genres', 'text_domain' ),
    'choose_from_most_used'      => __( 'Choose from the most used genres', 'text_domain' ),
);
$args = array(
    'labels'                     => $labels,
    'hierarchical'               => false,
    'public'                     => true,
    'show_ui'                    => true,
    'show_admin_column'          => true,
    'show_in_nav_menus'          => true,
    'show_tagcloud'              => true,
);
register_taxonomy( 'agencia', 'post', $args );

}

// Hook into the 'init' action
add_action( 'init', 'custom_taxonomy', 0 );
Was it helpful?

Solution 2

I'm trying everything. Finally i found the correct answer browsing in google after a lot of hours. The solution for everyone is:

<?php $terms = wp_get_post_terms($post->ID,'agencia');
$count = count($terms);
if ( $count > 0 ){
echo "<span>";
foreach ( $terms as $term ) {
echo $term->name . "<comma>, </comma>";
}
echo "</span>";} ?>

I created for delete the last comma with css:last-child

OTHER TIPS

The problem is you're using print_r to dump the content of $term_list. $term_list is an array, and print_r shows you that, along with its structure.

Try something like

foreach ($term_list as $term) {
    echo $term;
}

adding whatever wrapping tags you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top