0

I am using a simple if / else in a WordPress loop, with use of "Advanced custom field" plugin and I am loading an image and if not present, I want to load a fallback image. While using this loop, Wordpress shows both if and else conditions in the same time. What am I doing wrong? Many thanks for your help and advice.

<img class="profilepicture" src="<?php if (!empty(the_field('authors_image')))
{ the_field('authors_image'); } else  { echo(bloginfo('template_url') . "/img/profile.svg"); } ?>" alt=" profile ">

This is the result in html

<img class="profilepicture" src="http://example.com/wp-content/uploads/2016/12/picture-60966-516ob1f.jpghttp://example.com/wp-content/themes/IranDarJahan/img/profile.svg" alt=" profile ">
4
  • Both conditions are never fulfilled. You're wrong. Commented Dec 10, 2016 at 11:56
  • this is not possible. It is going to be if or else. Maybe the script you are trying isn't the right one. Check if the photo loads from another file Commented Dec 10, 2016 at 11:56
  • @u_mulder the same thing at the same time :D Commented Dec 10, 2016 at 11:57
  • Well this is the strange result in html <img class="profilepicture" src="example.com/wp-content/uploads/2016/12/…" alt=" profile "> Commented Dec 10, 2016 at 12:00

1 Answer 1

3

The problem is that your the_field() call in the if condition outputs the value, when in fact you want to check whether or not the value exists. Try this:

<img class="profilepicture" src="<?php if (!empty(get_field('authors_image')))
{ the_field('authors_image'); } else { echo(bloginfo('template_url') . "/img/profile.svg"); } ?>" alt=" profile ">
Sign up to request clarification or add additional context in comments.

2 Comments

@DanialKeshani You should accept this answer. And not change title to solved. Read tour.
P.S. just a tip to write a cleaner code - you can use if (get_field('authors_image')) { ... } as this checks if this field has a value

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.