• Right now I’m doing something like this:

    $town_array = get_the_terms($post->ID, ‘town-name’);
    foreach $town_array as $town_single {
    $town_name_array[] = $town_single->name;
    }
    $town_names_string = implode(“,”, $town_name_array);

    Is there a way to reduce that to a single line? There must be, but I can’t seem to make it happen. This is primarily a mental exercise, though there is a situation where I’d like to use it.

    Thanks in advance!

Viewing 3 replies - 1 through 3 (of 3 total)
  • I don’t think you can simplify it any further.

    One thing.. you’re missing your parenthesis around your foreach:

    foreach ($town_array as $town_single) {

    Second, you are going to need to define that $town_name_array variable first, or it’s going to throw a warning in PHP 5.4 and above.

    Thread Starter jptoews

    (@jptoews)

    Yeah, sorry, typed off the top of my head. But hopefully it successfully conveyed my question. Ah, I also forgot to put the code tags around it. Fail all the way around.

    Lol- No worries.

    Well,

    $town_array = get_the_terms($post->ID, 'town-name');

    … gets all the terms for that particular post ID; and assigns them to an array.

    foreach ($town_array as $town_single) {
        $town_name_array[] = $town_single->name;
    }

    .. takes that array… and loops through it… grabbing the name object from each one… and assigns it to another array.

    $town_names_string = implode(",", $town_name_array);

    … takes each item in the array.. and extracts it into a string (separated by commas).

    I’m not sure what you are using it for.. but this is the way I have always performed these tasks. I really don’t think you can refine the code any further.
    (Maybe some php genius can come prove me wrong ??

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Get list of term names in single line of code’ is closed to new replies.