Site icon Hip-Hop Website Design and Development

Shortcode and WP query using category attributes

I am trying to create a shortcode that shows the results of a custom query (calling menu items) for a takeaway business website. I have tried to get category attributes to work so that on the home page I can use [himenu cat=”special-offers”] which is the slug of the category I am using to show special offers. This works great no problems there however I am struggling to then impliment the following (as you’ll see from my code below)

1- on the ‘full menu’ page I’d like to use the same shortcode that displays all menu-items by just leaving the cat attribute blank
2 – on the full menu page, list all the menu-items under the respective category heading e.g.

BURGERS
item 1
item 2
item 3
item 4

KEBABS
item 1
item 2
item 3

etc.

I have setup categories for the custom post type so I think I need to find the categories and loop through them before the query runs? any advice would be great, I’ve spent a whole morning on thsi unsuccessfully.

Thanks

//MENU SHORTCODE
add_shortcode( 'himenu', 'cat_post' );

function cat_post($atts){

    // attributes for shortcode
   if (isset($atts['cat'])) {$cat = $atts['cat'];} else {return;}
   if (isset($atts['posts_per_page'])) {$posts_per_page = $atts['posts_per_page'];} else {$posts_per_page = -1;}

   // get the category posts
   $category = get_category_by_slug($cat);
   if (!is_object($category)) {return;}

   $args = array(
        'cat' => $category->term_id,
        'post_type' => menu_item,
        'posts_per_page' => $posts_per_page,
        'order' => 'ASC',
        'orderby' => 'title'
   );

$query = new WP_Query($args);
        while ($query->have_posts()) : $query->the_post(); ?>   

            <div class="indi-menu-item"> 
                <div class="menu-item-column">
                    <h5> <?php  
                    if($cat === 'special-offers'){
                        echo 'Special Offers';
                    } else {
                        the_category();
                    }
                     ?></h5>
                    <div class="menu-item-meta">
                        <h4> <?php the_title(); ?></h4>                    
                        <p><?php the_field('description')?></p>
                    </div>
                </div>
                <div class="menu-item-column">
                    <h2>£<?php the_field('price'); ?></h2>
                </div>
            </div>    


       <?php endwhile;
        wp_reset_postdata(); // reset the query 

}

    wp_reset_query();//reset the global variable related to post loop
     ?>