Search code examples
phphtmlwordpresswoocommerceshortcode

Display a warning message in a shortcode for users without an order


In the functions.php file I have this shortcode which shows the download button of the last order placed by a woocommerce customer. Everything works fine for customers who have bought something, however if a customer has no downloads or no order, the layout breaks. I suppose this happens because there is nothing to be displayed.

So I would like to display a message for those who have no download or have not placed an order, I tried with else but it didn't work.

Sorry but I'm relatively new to php, can anyone help me figure out how to introduce a warning message?

add_shortcode( 'order_download' , 'last_order_info_08' );
function last_order_info_08( $downloads ){
    
$customer = new WC_Customer( get_current_user_id() );
$last_order = $customer->get_last_order();
$downloads = $last_order->get_downloadable_items();

if ($downloads) {
    wc_get_template(
        'button-downloads.php',
        array(
            'downloads'  => $downloads,
            'show_title' => true,
        )
    );
}
}

Solution

  • I modified the code a bit and should suit your need. You should be able to just replace the current code with this. Tested and confirmed locally on any page the shortcode is added it displayed. If you have some odd CSS setup it may or may not display correct on your site.

    add_shortcode( 'order_download' , 'last_order_info_08' );
    function last_order_info_08( $downloads ){
    
        $customer = new WC_Customer( get_current_user_id() );
    
        $last_order = $customer->get_last_order();
    
        $shop_url = get_permalink( wc_get_page_id( 'shop' ) );
    
        // Check to see if they have an order
        if ($last_order) {
            // Get download items from last order.
            $downloads = $last_order->get_downloadable_items();
            // Check to see if it contains downloadable items
            if ($downloads) {
                wc_get_template(
                    'button-downloads.php',
                    array(
                        'downloads'  => $downloads,
                        'show_title' => true,
                    )
                );
            } else {
                wc_add_notice( '<a class="woocommerce-Button button" href="'. $shop_url .'"> Browse products</a> No downloads available yet.', 'notice' );
            }
        } else {
            wc_add_notice( '<a class="woocommerce-Button button" href="'. $shop_url .'"> Browse products</a> No downloads available yet.', 'notice' );
        }
        // HERE we print the notices
        wc_print_notices();
    }