I'm trying to get some php code to work in a shortcode.
Here is what i did in woocommerce dashboard.php. This code shows the data of the last order placed by the customer, everything works perfectly. As you can see it contains if, endif and else.
<?php
// For logged in users only
if ( is_user_logged_in() ) :
// Get the current WC_Customer instance Object
$customer = new WC_Customer( get_current_user_id() );
// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();
?>
<?php if( is_a($last_order, 'WC_Order') ) : ?>
<?php foreach ( $last_order->get_items() as $item ) : ?>
<div class="last_order_items"><?php echo $item->get_name(); ?></div>
<div class="last_order_items"><?php echo $item->get_total(); ?>€</div>
<div class="order_number">#<?php echo $last_order->get_order_number(); ?> </div>
<div class="order_number">Data acquisto <?php echo $last_order->get_date_created()->date('d/m/Y - H:i'); ?> </div>
<div class="order_number">Stato dell'ordine <?php echo esc_html( wc_get_order_status_name( $last_order->get_status() ) ); ?>
<?php endforeach; ?>
<?php else : ?>
<div class="woocommerce-message woocommerce-message--info woocommerce-Message woocommerce-Message--info woocommerce-info">
<a class="woocommerce-Button button" href="<?php echo esc_url( apply_filters( 'woocommerce_return_to_shop_redirect', wc_get_page_permalink( 'shop' ) ) ); ?>"><?php esc_html_e( 'Browse products', 'woocommerce' ); ?></a>
<?php esc_html_e( 'No order has been made yet.', 'woocommerce' ); ?>
</div>
<?php endif; ?>
<?php endif; ?>
Here is what I did in the functions.php file. The shortcode works fine, but if user is not logged in or has not placed an order, an error occurs. In dashboard.php file the error is not there because the if (is_user_logged_in ()) part exists and the else part which shows the message when a user has not placed any order.
//// LAST ORDER ON DASHBOARD WOOCOMMERCE SHORTCODE ////
add_shortcode( 'short_test' , 'test' );
function test(){
$customer = new WC_Customer( get_current_user_id() );
$last_order = $customer->get_last_order();
return $last_order->get_order_number();
}
How can i implement if, endif and else in this shortcode ? I would like to be able to show data only to logged in users, and for those who have not placed any orders I would like to display a message just like I did in the dashboard.php file. I tried a number of ways but couldn't. I would like to use the shortcode because it is more convenient for me, moreover I prefer to keep the woocommerce templates "clean" and write everything directly in the functions.php file
Sorry, but I'm a fan and don't have a lot of knowledge on the subject.