CharlyAnderson
CharlyAnderson

Reputation: 737

Wordpress End If Statements

Apologies, PHP is not my strongest area so this might seem super easy to others.

I am trying to implement a statement to say, when there is something in my WooCommerce Cart to show the cart. If there's nothing in the cart then show nothing.

The code I have so far is:

<?php if ( sizeof( $woocommerce->cart->cart_contents ) == 0 ) {
  // The cart is empty
} else {

<div class="header-cart-inner">
  <a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf (_n( '%d item', '%d items', WC()->cart->cart_contents_count ), WC()->cart->cart_contents_count ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>
</div>

} ?>

The code doesn't work and keeps giving me syntax errors.

Upvotes: 0

Views: 80

Answers (2)

Shubham Kumar
Shubham Kumar

Reputation: 1

First-of-all you need to use "woocommerce_check_cart_items" hook to check cart item. And also you didn't close the php tag before starting to the HTML.

Here is an example :

<?php
function E_Coding_Hub_Coder() {

    if ( WC()->cart->get_cart_contents_count() == 0 ) {
        wc_print_notice( __( '(E-Coding Hub Message) Your Cart is Empty', 'woocommerce' ), 'notice');
    } else {
        ?>
        <div class="header-cart-inner">
            <a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf (_n( '%d item', '%d items', WC()->cart->cart_contents_count ), WC()->cart->cart_contents_count ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>
       </div>
       <?php
    } 
}

// Add to cart page
add_action( 'woocommerce_check_cart_items', 'E_Coding_Hub_Coder' );

// Add to shop archives & product pages
add_action( 'woocommerce_before_main_content', 'E_Coding_Hub_Coder' );

Upvotes: 0

Gerton
Gerton

Reputation: 686

<?php if ( sizeof( $woocommerce->cart->cart_contents ) == 0 ) {
  // The cart is empty
} else { ?>

<div class="header-cart-inner">
  <a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf (_n( '%d item', '%d items', WC()->cart->cart_contents_count ), WC()->cart->cart_contents_count ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>
</div>
<?php } ?>

That should do!

Explanation :
All PHP code is going between <?php #php code# ?> everything between these two tags is going to be compiled by the PHP engine. You didn't close your PHP after else { because of this your next piece of script <div clas... is going to be interpreted as PHP code. Now the PHP engine is going to read this and doesn't know what to make of it since it's not PHP and will throw an error.

Upvotes: 2

Related Questions