2021年1月19日星期二

Define variable with IF ELSE statement - Wordpress

I'm trying to define and output a $store_icon variable based on the IF ELSE condition.

I'd like to show a store icon if the store icon image exists, if it doesn't, then I'd like to show just a regular profile avatar (using an existing shortcode)

This is as far as I can get:

$store_icon_src = wp_get_attachment_image_src( get_user_meta( $vendor_id, '_wcv_store_icon_id', true ), array( 40, 40  ) );   $store_icon     = '';    if ( is_array( $store_icon_src ) && !empty($store_icon_src) ) {       $store_icon = '<img src="'. $store_icon_src[0].'" alt="Store Name" class="store-icon" width="40" height="40" />';  } else {       $store_icon = do_shortcode( '[profile-avatar]' );  }    echo '<div class="store-icon">'. $store_icon .'</div>';         

It kinda works, but I need both options to be output inside the echo html div tags.

Currently they're not, the first option seems to be called outside the echo.

What am I doing wrong here?

UPDATE: I came across to 'Ternary operator' from another question, so I'm trying this:

$store_icon   = (is_array( $store_icon_src ) && !empty($store_icon_src) ) ? '<img src="'. $store_icon_src[0].'" alt="My Store" class="store-icon" width="40" height="40" />' : do_shortcode( '[profile-avatar]' );  

And then output:

ob_start();  echo '<div class="store-icon">'. $store_icon .'</div>';  $output = ob_get_clean();  return $output;  

But nothing changed, the first img is still called outside the echo div tags.

https://stackoverflow.com/questions/65802043/define-variable-with-if-else-statement-wordpress January 20, 2021 at 09:54AM

没有评论:

发表评论