【发布时间】:2023-03-30 01:23:02
【问题描述】:
我正在尝试让一些 php 代码在简码中工作。
这是我在 woocommerce dashboard.php 中所做的。这段代码显示了客户最后一次下订单的数据,一切正常。如您所见,它包含 if、endif 和 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; ?>
这是我在 functions.php 文件中所做的。简码工作正常,但如果用户未登录或未下订单,则会发生错误。在dashboard.php 文件中不存在错误,因为if (is_user_logged_in ()) 部分存在,而else 部分在用户未下任何订单时显示消息。
//// 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();
}
如何在这个简码中实现 if、endif 和 else?我希望能够只向登录用户显示数据,对于那些没有下任何订单的用户,我希望像在dashboard.php 文件中那样显示一条消息。我尝试了很多方法,但都做不到。我想使用简码,因为它对我来说更方便,而且我更喜欢保持 woocommerce 模板“干净”并将所有内容直接写在 functions.php 文件中
抱歉,我是粉丝,对此主题了解不多。
【问题讨论】:
标签: php html wordpress woocommerce shortcode