0

I have the required code for what I want

    <?php if ( is_singular() ) {
 <?php if (get_post_meta(get_the_ID(), 'square_image', true)) { ?> <img src="<?php echo get_post_meta($post->ID, 'square_image', true); ?>"/>  <?php } else { ?> <?php the_post_thumbnail( 'thumbnail' );?> <?php } ?>
} else {
  
}
    ?>

but I simply don't know how to make the PHP work along with HTML, and inside another PHP code. Please help me make this code work

thank you

1
  • When you open a PHP tag you have to close it before you can open another one. Your code has <?php ..... <?php at the top which is invalid
    – Tom J Nowell
    Jul 31, 2022 at 18:55

1 Answer 1

5

From your code the proper structure would be

if ( is_singular() ) {
    if (get_post_meta(get_the_ID(), 'square_image', true)) {
        echo '<img src="' . get_post_meta($post->ID, 'square_image', true) . '"/>';
    } else {
        the_post_thumbnail( 'thumbnail' );
    }
}

We can make it a bit better by creating a variable that will contain the meta data so we don't have to call the same function twice.

if (is_singular()) {
    if (!empty($square_image = get_post_meta(get_the_ID(), 'square_image', true))) {
        echo '<img src="' . $square_image . '"/>';
    } else {
        the_post_thumbnail('thumbnail');
    }
}

Now because our conditions contain just one line of code we can remove the {}

if (is_singular()) {
    if (!empty($square_image = get_post_meta(get_the_ID(), 'square_image', true))) echo '<img src="' . $square_image . '"/>';
    else the_post_thumbnail('thumbnail');
}

The official php documentation goes into details about working with php and html, see https://www.php.net/manual/en/faq.html.php.
This might also help, https://www.php.net/manual/en/language.operators.string.php, this goes into detail (not much) about how to concatenate strings

Your Answer

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

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