1

I'd like to retrieve tags data and output it in post body inside a template.

<a class="tag-button w-button" href="<!--Tag Link-->"
style="background-color: <!--Tag Color--> ">
<!--Tag Name--> </a>

I use default WP Taxonomy for tags, and I created a custom field "tag-color" for Tags using ACF. Does anyone have an idea of what is the best way to do that?

4
  • Sure, that's possible. But where are you thinking of putting that code? In a template, a function, a widget? That determines how you can retrieve the data.
    – cjbj
    Commented Sep 25, 2016 at 12:52
  • @cjbj I want to put it inside post template
    – ERDFX
    Commented Sep 25, 2016 at 12:59
  • A post can have many tags. All have the same color or are they different by tag?
    – cjbj
    Commented Sep 25, 2016 at 13:02
  • @cjbj yeah i want to output every tag with each having different color. Color is specified in "tag-color" custom field.
    – ERDFX
    Commented Sep 25, 2016 at 13:04

1 Answer 1

1

There are two ways to approach this: modify the existing the_tags function or build your own.

the_tags ultimately relies on get_the_term_list, which returns a list of hyperlinked tags. You would have to use regular expressions to add classes and styles to that using a filter. That would be quite cumbersome.

So, my preferred approach would be to construct a function yourself. Start with an array of tags and loop through them:

$all_tags = wp_get_post_tags (get_the_ID(), array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all'));
$output = "";
foreach ($all_tags as $tag) {
  $tag_style =  // get that from ACF
  $tag_link  =  get_tag_link($tag->term_id);
  $tag_name  =  $tag->name;
  $output .= '<a class="tag-button w-button" href="' . $tag_link . '" style="' . $tag_style . '">' . $tag_name . '</a>';
  }
echo $output;

Note: I didn't test this code, so some debuggin may be necessarry.

7
  • it gives me in an error on the line with $tag_link: "Fatal error: Cannot use object of type WP_Term as array in..."
    – ERDFX
    Commented Sep 25, 2016 at 14:01
  • Like I said debugging .. the function apparently returns an object, not an array, so its $tag->term_id to get to the item.
    – cjbj
    Commented Sep 25, 2016 at 14:16
  • Thanks now its working! However except $tag_style ( $tag_style = get_field("tag_color", $tag->term_id);)
    – ERDFX
    Commented Sep 25, 2016 at 14:39
  • Glad it works. I'll update the answer for the object stuff. Please accept the answer to let the system know this question can be closed.
    – cjbj
    Commented Sep 25, 2016 at 14:40
  • Not exactly, I still cant retrieve ACF field "tag_color" :(
    – ERDFX
    Commented Sep 25, 2016 at 14:47

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.