Search code examples
phpwordpresstaxonomycustom-fields

PHP Wordpress code echo's slug not term?


Does anybody know how I can change the below code for my custom taxonomy (created in the Magic Fields 2 plugin) to solve my problem. I would like it to echo the name of the selected value rather than slug format. e.g. I'd like to echo Client 1 and Client 2 instead of client-1 and client-2 as it currently does.

I'd like to display multiword names with spaces and correct capitalisation e.g. Joe Bloggs Associates not joe-bloggs-associates.

project_statistics_client is the name of the field created in Magic Fields. The Type of the custom field is Term dropdown and populates with the values from my custom Taxonomy called Clients. This field is located inside of a field group that's named project_statistics but I am not sure if the group name influences the code or not?

Also please note that all the above is in a custom post type called Projects.

I have checked plugin help but still not sure:

Here is the code:

<?php $clients = get_field('project_statistics_client');
    foreach($clients as $client){
        echo '<div>' . $client . '</div>';
    } ?>

Solution

  •     global $post;
        $taxonomy = 'your taxonomy';
        $terms = get_the_terms($post->ID, $taxonomy);
        if ( is_array($terms) ) {
            echo(implode(',', wp_list_pluck($terms, 'name')));
        }
    

    Magic Fields 2 only provides a nice GUI to the basic WordPress taxomony feature and therefore all the WordPress taxonomy functions can be used. In particular, get_the_terms() may be used to get the categories of a post. This returns an array of objects (a post may be in multiple categories). Also, you need to extract the 'name' field from the objects.