How not to have Warning if I leave empty in the formula multiplication discount?

Asked

Viewed 41 times

0

How not to have the Warning: Division by zero in if I even choose to put zero. I want to have the option to leave the price empty, but if I leave it empty, it multiplies as it is in the formula of the discount and gives error. Have to put not show this div if the deal_price and deal_sale_price are empty or 0?

<ul class="deal-single-value">
    <?php
      $deal_price = get_post_meta( get_the_ID(), 'deal_price', true);
      $deal_sale_price = get_post_meta( get_the_ID(), 'deal_sale_price', true);
    ?>

    <li>
        <p><?php esc_html_e( 'Preço Antigo', 'site' ) ?></p>
        <?php echo site_format_price_number( $deal_price ) ?>
    </li>
    <li>
        <p><?php esc_html_e( 'Desconto de', 'site' ) ?></p>
        <?php echo round( 100 - ( $deal_sale_price / $deal_price ) * 100 ).'%'; ?>
    </li>
    <li>
        <p><?php esc_html_e( 'Você economizou', 'site' ) ?></p>
        <?php echo format_price_number( $deal_price - $deal_sale_price ) ?>
    </li>
</ul>

2 answers

0


Just put a if before making the calculation:

<ul class="deal-single-value">
<?php
  $deal_price = get_post_meta( get_the_ID(), 'deal_price', true);
  $deal_sale_price = get_post_meta( get_the_ID(), 'deal_sale_price', true);
?>

<li>
    <p><?php esc_html_e( 'Preço Antigo', 'site' ) ?></p>
    <?php echo site_format_price_number( $deal_price ) ?>
</li>

<?php if(!empty($deal_sale_price) && !empty($deal_price)):?>
<li>
    <p><?php esc_html_e( 'Desconto de', 'site' ) ?></p>
    <?php echo round( 100 - ( $deal_sale_price / $deal_price ) * 100 ).'%'; ?>
</li>
<?php endif;?>

<li>
    <p><?php esc_html_e( 'Você economizou', 'site' ) ?></p>
    <?php echo format_price_number( $deal_price - $deal_sale_price ) ?>
</li>

  • Thanks a lot, Kenny. It worked

  • Arrange Peri, consider marking the answer as correct so that other people can also enjoy the reference! =)

0

The divisor cannot be zero because no number is divisible by zero.

Here’s an example of how you can solve by applying a ternary conditional.

<?php echo round( 100 - ($deal_price > 0?($deal_sale_price / $deal_price):0) * 100 ).'%'; ?>
  • Thank you very much, Daniel. It worked here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.