0

I need to make a PHP variable that takes get_template_directory_uri(), appends /assets/images and appends the_sub_field('icon') and appends the string -colored.png how do I do this?

The correct output needs to looks like this:

...assets/images/icon-linkedin-colored.png

...assets/images/icon-facebook-colored.png

I've confirmed the output of <div><?php echo the_sub_field('icon') ?></div> is correct.

The first thing I tried:

<?php $iconName = echo get_template_directory_uri() + '/assets/images/' + the_sub_field('icon') + '-colored.png'; ?>

In VS code I just get "No quick fixes available which doesn't help me.

PHP - concatenate or directly insert variables in string

I then tried

<?php $iconName = get_template_directory_uri() . '/assets/images/' . the_sub_field('icon') . '-colored.png'; ?>

Because I forgot you do . for trying strings (or string concactenation)

But the output of this is

.../assets/images/-colored.png

Why is it JUST giving -colored.png? What is wrong with my string operation?

It needs to be .../assets/images/icon-linkedin-colored.png

ADyson
  • 57,178
  • 14
  • 51
  • 63
kawnah
  • 3,204
  • 8
  • 53
  • 103
  • Looks like your functions aren't returning what they should. – Tangentially Perpendicular Jul 22 '21 at 22:31
  • The last attempt (without echo and with `.`, which is correct, instead of `+`, which is JS, not PHP) should work if you change `the_sub_field('icon')` to `get_sub_field('icon')`. The difference is that `the_sub_field()` doesn't return the value, it outputs it (echoes it) while `get_sub_field()` returns it (which is what you want/need when you want to concatenate it) – M. Eriksson Jul 22 '21 at 22:31
  • @MagnusEriksson okay, that was it, but I don't know why it works now. Is it because "get_sub_field" "returns" a value or something? – kawnah Jul 22 '21 at 22:35
  • I literally told you that in my comment :-) When concatenating strings, the functions needs to _return_ the value so it can be concatenated. – M. Eriksson Jul 22 '21 at 22:35
  • Test with `echo get_sub_field('icon');`. – StackSlave Jul 22 '21 at 22:42
  • @MagnusEriksson your comment with the explanation wasnt published when I responded. – kawnah Jul 23 '21 at 15:25

0 Answers0