Make PHP work with HTML tags

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

Topic php html Wordpress

Category Web


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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.