I am working on a custom WordPress theme.
I am trying to show a list of categories (as headers) for a custom post type, and under the heading of each category I would like to specify message headers and one custom field. I am using a types plugin. I know a little php and have some WordPress experience, but not enough to get it right.
Example:
Custom message type: menu item
Custom field for this message type: Product price
Category: Sandwich Fillings
Category: Soups
Desired Result:
Sandwich fill
Cheese - £ #. ##
Vem - £ #. ##
Tuna - £ #. ##
...
Soups
Tomato
Chicken
Vegetable
The idea will be to add new categories on the fly (for example, one day they can start selling melts), and for WP - iterate over categories as new ones are added, preserving from availability to hard code in new categories per page as you add.
Here is what I still have:
<?php $args = array( 'post_type' => 'menu-item', 'orderby' => 'name', 'parent' => 0 ); $categories = get_categories( $args ); foreach ( $categories as $category ) { $posts = get_posts($args); $item_price = types_render_field( "item-price" ); echo '<h2>' . $category->name . '</h2>'; ?> <ul><?php foreach($posts as $post) { ?> <li><?php the_title(); ?>, <?php echo $item_price; ?></li> <?php } } ?>
What I get is:
Sandwiches
Tomato,
Swiss cheese,
French Brie,
French Brie,
...
Soups
Tomato, £ 2.60
Swiss cheese, £ 2.60
French Brie, £ 2.60
French Brie, £ 2.60
Any help would be appreciated!
UPDATE
That helped:
<?php $args = array( 'post_type' => 'menu-item' ); $categories = get_categories( $args ); $posts = get_posts($args); foreach ( $categories as $category ) { echo '<h2>' . $category->name . '</h2>'; ?> <div class="menu-items-container"> <?php foreach($posts as $post) { ?> <?php $item_price = types_render_field( "item-price" ); ?> <?php if (in_category($category)) { ?> <p><?php the_title(); ?>, <?php echo $item_price; ?></p> <?php } ?> <?php } ?> </div> <?php } ?>
And it gives me the results that I was looking for. I came across this correction through experiments and a fluke, so I know that this may not be the best practice - advice or suggestions for improvement are welcome!
source share